-
Notifications
You must be signed in to change notification settings - Fork 2
/
LargestRectangleHistogram.java
38 lines (33 loc) · 1.28 KB
/
LargestRectangleHistogram.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
package src.java.hard.stack;
import java.util.LinkedList;
class LargestRectangleHistogram {
public int largestRectangleArea(int[] height) {
// Start typing your Java solution below
// DO NOT write main() function
if (height==null || height.length==0) return 0;
LinkedList<Integer> heightStack = new LinkedList<Integer>();
LinkedList<Integer> indexStack = new LinkedList<Integer>();
int ret=0;
for (int i=0; i<height.length; i++){
if (heightStack.isEmpty() || heightStack.peek()<height[i]){
heightStack.push(height[i]);
indexStack.push(i);
}
else if (heightStack.peek()>height[i]){
int in = 0;
while(!heightStack.isEmpty() && heightStack.peek()>height[i]){
in = indexStack.pop();
int temp = heightStack.pop()*(i-in);
ret = Math.max(ret, temp);
}
heightStack.push(height[i]);
indexStack.push(in);
}
}
while(!heightStack.isEmpty()){
int temp = heightStack.pop()*(height.length-indexStack.pop());
ret = Math.max(ret, temp);
}
return ret;
}
}