-
Notifications
You must be signed in to change notification settings - Fork 0
/
Largest Rectangle in Histogram
52 lines (52 loc) · 1.16 KB
/
Largest Rectangle in Histogram
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
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int N=heights.size();
stack<int>st;
int leftSmall[N];
int rightSmall[N];
int Area=0;
for(int i=0;i<N;i++)
{
while(!st.empty() && heights[st.top()]>=heights[i])
{
st.pop();
}
if(st.empty())
{
leftSmall[i]=0;
}
else
{
leftSmall[i]=st.top()+1;
}
st.push(i);
}
while(!st.empty())
{
st.pop();
}
for(int i=N-1;i>=0;i--)
{
while(!st.empty() && heights[st.top()]>=heights[i] )
{
st.pop();
}
if(st.empty())
{
rightSmall[i]=N-1;
}
else
{
rightSmall[i]=st.top()-1;
}
st.push(i);
}
int maxArea=0;
for(int i=0;i<N;i++)
{
maxArea=max(maxArea, heights[i]*(rightSmall[i]-leftSmall[i]+1));
}
return maxArea;
}
};