-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlargest-rectangle-in-histogram.java
59 lines (51 loc) · 1.15 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
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public int largestRectangleArea(int[] heights) {
//nextSmallerElementsonTheRight
int[] nsr=new int[heights.length];
Stack<Integer> st=new Stack<>();
st.push(heights.length-1);
for(int i=heights.length-1;i>=0;i--)
{
//pop all the greater elements
while(st.size()>0&&heights[st.peek()]>=heights[i])
{
st.pop();
}
if(st.size()==0)
{
nsr[i]=heights.length;
}
else
{
nsr[i]=st.peek();
}
st.push(i);
}
int[] nsl=new int[heights.length];
st=new Stack<>();
st.push(0);
for(int i=0;i<heights.length;i++)
{
//pop all the greater elements
while(st.size()>0&&heights[st.peek()]>=heights[i])
{
st.pop();
}
if(st.size()==0)
{
nsl[i]=-1;
}
else
{
nsl[i]=st.peek();
}
st.push(i);
}
int max=0;
for(int i=0;i<heights.length;i++)
{
max=Math.max(max,heights[i]*(nsr[i]-nsl[i]-1));
}
return max;
}
}