-
Notifications
You must be signed in to change notification settings - Fork 0
/
84.largest-rectangle-in-histogram.java
47 lines (35 loc) · 1.32 KB
/
84.largest-rectangle-in-histogram.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public int largestRectangleArea(int[] heights) {
if(heights.length == 0)
return 0;
int maxarea = 0;
int minarea = Integer.MAX_VALUE;
// for(int i=0;i<heights.length;i++){
// minarea = heights[i];
// maxarea = Math.max(maxarea, minarea);
// for(int j =i+1;j<heights.length;j++){
// minarea = Math.min(minarea, heights[j]);
// maxarea = Math.max(maxarea, minarea*(j-i+1));
// }
// // if(max)
// }
Stack<Integer> stk = new Stack<Integer>();
int i = 0;
int n = heights.length;
while(i<n){
if(stk.isEmpty() || heights[stk.peek()] <= heights[i])
stk.push(i++);
else{
int tpind = stk.peek();
stk.pop();
maxarea = Math.max(heights[tpind]*(stk.isEmpty() ? i : i-stk.peek()-1), maxarea);
}
}
while(!stk.isEmpty()){
int tpind = stk.peek();
stk.pop();
maxarea = Math.max(heights[tpind]*(stk.isEmpty() ? i : i-stk.peek()-1), maxarea);
}
return maxarea;
}
}