-
Notifications
You must be signed in to change notification settings - Fork 656
/
Copy pathlargestRectangleHistorgram2passJava
38 lines (31 loc) · 1.09 KB
/
largestRectangleHistorgram2passJava
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
class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.length;
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[st.peek()] >= heights[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[st.peek()] >= heights[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[i] * (rightSmall[i] - leftSmall[i] + 1));
}
return maxA;
}
}