-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargestRectangleInHistogram.java
53 lines (38 loc) · 1.57 KB
/
LargestRectangleInHistogram.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
48
49
50
51
52
53
import java.util.AbstractMap;
import java.util.Map;
import java.util.Stack;
public class LargestRectangleInHistogram {
public int largestRectangleArea(int[] heights) {
Stack<Map.Entry<Integer, Integer>> stack = new Stack<>();
int maxArea = 0;
for (int i = 0; i < heights.length; i++) {
if (stack.isEmpty()) {
stack.push(new AbstractMap.SimpleEntry<>(i, heights[i]));
continue;
}
if (heights[i] < stack.peek().getValue()) {
while (!stack.isEmpty() && heights[i] < stack.peek().getValue()) {
int areaCovered = (i - stack.peek().getKey()) * stack.peek().getValue();
maxArea = Math.max(maxArea, areaCovered);
System.out.println(stack);
stack.pop();
}
stack.push(new AbstractMap.SimpleEntry<>(i, heights[i]));
} else {
stack.push(new AbstractMap.SimpleEntry<>(i, heights[i]));
}
}
if (!stack.isEmpty()) {
while (!stack.isEmpty()) {
maxArea = Math.max(maxArea, (heights.length - stack.peek().getKey()) * stack.peek().getValue());
stack.pop();
}
}
return maxArea;
}
public static void main(String[] args) {
LargestRectangleInHistogram largestRectangleInHistogram = new LargestRectangleInHistogram();
int[] heights = {2,1,2};
System.out.println(largestRectangleInHistogram.largestRectangleArea(heights));
}
}