-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargest Rectangle in Histogram.java
46 lines (42 loc) · 1.19 KB
/
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
import java.util.Stack;
class Solution {
public int largestRectangleArea(int[] heights) {
Stack<Pair> leftSt = new Stack();
int[] leftIndex = new int[heights.length];
for (int i = 0; i < heights.length; i++) {
while (!leftSt.isEmpty() && leftSt.peek().height >= heights[i]) {
leftSt.pop();
}
if (leftSt.isEmpty())
leftIndex[i] = -1;
else
leftIndex[i] = leftSt.peek().index;
leftSt.push(new Pair(heights[i], i));
}
Stack<Pair> rightSt = new Stack();
int[] rightIndex = new int[heights.length];
for (int i = heights.length - 1; i >= 0; i--) {
while (!rightSt.isEmpty() && rightSt.peek().height >= heights[i]) {
rightSt.pop();
}
if (rightSt.isEmpty())
rightIndex[i] = heights.length;
else
rightIndex[i] = rightSt.peek().index;
rightSt.push(new Pair(heights[i], i));
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < heights.length; i++) {
max = Math.max(max, heights[i] * (rightIndex[i] - leftIndex[i] - 1));
}
return max;
}
}
class Pair {
int height;
int index;
Pair(int height, int index) {
this.height = height;
this.index = index;
}
}