-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargestRectangleInHistogram.java
45 lines (34 loc) · 1.21 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
import java.util.*;
public class Solution {
public static int largestRectangle(ArrayList < Integer > heights) {
int n = heights.size();
Stack < Integer > st = new Stack < > ();
int leftSmall[] = new int[n];
int rightSmall[] = new int[n];
for (int i = 0; i < n; i++) {
while (!st.isEmpty() && heights.get(st.peek()) >= heights.get(i)) {
st.pop();
}
if (st.isEmpty())
leftSmall[i] = 0;
else
leftSmall[i] = st.peek() + 1;
st.push(i);
}
// clear the stack to be re-used
while (!st.isEmpty()) st.pop();
for (int i = n - 1; i >= 0; i--) {
while (!st.isEmpty() && heights.get(st.peek()) >= heights.get(i)) {
st.pop();
}
if (st.isEmpty()) rightSmall[i] = n - 1;
else rightSmall[i] = st.peek() - 1;
st.push(i);
}
int maxA = 0;
for (int i = 0; i < n; i++) {
maxA = Math.max(maxA, heights.get(i) * (rightSmall[i] - leftSmall[i] + 1));
}
return maxA;
}
}