-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0084-largest-rectangle-in-histogram.cpp
54 lines (53 loc) · 1.43 KB
/
0084-largest-rectangle-in-histogram.cpp
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
class Solution {
public:
vector<int>findNextSmallToRight(vector<int>&arr)
{
int n=arr.size();
vector<int>nextSmall(n);
stack<int>st;
for(int i=n-1;i>=0;i--)
{
while(!st.empty()&&arr[st.top()]>=arr[i])
{
st.pop();
}
if(!st.empty())
nextSmall[i]=st.top();
else
nextSmall[i]=n;
st.push(i);
}
return nextSmall;
}
vector<int>findNextSmallToLeft(vector<int>&arr)
{
int n=arr.size();
vector<int>nextSmall(n);
stack<int>st;
for(int i=0;i<n;i++)
{
while(!st.empty()&&arr[st.top()]>=arr[i])
{
st.pop();
}
if(!st.empty())
nextSmall[i]=st.top();
else
nextSmall[i]=-1;
st.push(i);
}
return nextSmall;
}
int largestRectangleArea(vector<int>& heights) {
vector<int>nextSmallToLeft=findNextSmallToLeft(heights);
vector<int>nextSmallToRight=findNextSmallToRight(heights);
int largestRectangle=0;
for(int i=0;i<heights.size();i++)
{
int length=nextSmallToRight[i]-nextSmallToLeft[i]-1;
cout<<length<<"\n";
largestRectangle=max(largestRectangle,length*heights[i]);
}
return largestRectangle;
}
};