1
+ // This is from heartfire.cc.
2
+ import java .util .Stack ;
3
+ public class Solution {
4
+ public int largestRectangleArea (int [] height ) {
5
+ // Start typing your Java solution below
6
+ // DO NOT write main() function
7
+
8
+ //for every i, height[0...i] is a subproblem
9
+ int i = 0 , max = 0 ;
10
+ Stack <Ele > st = new Stack <Ele >();
11
+ while (i < height .length ) {
12
+ if (st .empty () || height [i ] > st .peek ().height ) {
13
+ st .push (new Ele (height [i ], i ));
14
+ }
15
+ else if (st .peek ().height > height [i ]){ //need to ignore the case where st.peek().height == height[i]
16
+ int prev = 0 ;
17
+ while (!st .empty () && st .peek ().height > height [i ]) {
18
+ Ele e = st .pop ();
19
+ prev = e .index ;
20
+ max = Math .max (max , e .height * (i - e .index ));
21
+ }
22
+ st .push (new Ele (height [i ], prev ));
23
+ }
24
+ i ++;
25
+ }
26
+
27
+ //stack may contain a series of ascending heights
28
+ while (!st .empty ()) {
29
+ Ele e = st .pop ();
30
+ max = Math .max (max , e .height *(i - e .index ));
31
+ }
32
+
33
+ return max ;
34
+ }
35
+
36
+ private class Ele {
37
+ int height ;
38
+ int index ;
39
+
40
+ public Ele (int h , int i ) {
41
+ this .height = h ;
42
+ this .index = i ;
43
+ }
44
+ }
45
+ }
46
+
47
+ // My recursive version, but cannot pass large test.
48
+ public class Solution {
49
+ public int largestRectangleArea (int [] height ) {
50
+ // Start typing your Java solution below
51
+ // DO NOT write main() function
52
+ if (height .length < 1 ){
53
+ return 0 ;
54
+ }
55
+ if (height .length == 1 ){
56
+ return height [0 ];
57
+ }
58
+ int l = 0 ;
59
+ int r = height .length - 1 ;
60
+ return findLargestRectangle (height , l , r );
61
+ }
62
+
63
+ public int findLargestRectangle (int [] height , int l , int r ){
64
+ if (l == r ){
65
+ return height [l ];
66
+ }
67
+ int min = extractMin (height , l , r );
68
+ int combine = (r - l + 1 ) * height [min ];
69
+ int left = (l < min ) ? findLargestRectangle (height , l , min - 1 ) : height [l ];
70
+ int right = (min < r ) ? findLargestRectangle (height , min + 1 , r ) : height [r ];
71
+ int bigger = (left > right )?left :right ;
72
+ return (combine > bigger )?combine : bigger ;
73
+ }
74
+
75
+ // return the index of the minimum element between l and r, inclusive.
76
+ public int extractMin (int [] height , int l , int r ){
77
+ int min = l ;
78
+ for (int i = l + 1 ; i <= r ; i ++){
79
+ if (height [i ] < height [min ]){
80
+ min = i ;
81
+ }
82
+ }
83
+ return min ;
84
+ }
85
+ }
0 commit comments