Skip to content

Commit 30a3ccc

Browse files
committed
Time: 771 ms (5.01%), Space: 81.4 MB (50.14%) - LeetHub
1 parent ea3dfe4 commit 30a3ccc

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class Solution {
2+
public:
3+
vector<int>findNextSmallToRight(vector<int>&arr)
4+
{
5+
int n=arr.size();
6+
vector<int>nextSmall(n);
7+
stack<int>st;
8+
for(int i=n-1;i>=0;i--)
9+
{
10+
while(!st.empty()&&arr[st.top()]>=arr[i])
11+
{
12+
st.pop();
13+
}
14+
if(!st.empty())
15+
nextSmall[i]=st.top();
16+
else
17+
nextSmall[i]=n;
18+
st.push(i);
19+
}
20+
return nextSmall;
21+
}
22+
vector<int>findNextSmallToLeft(vector<int>&arr)
23+
{
24+
int n=arr.size();
25+
vector<int>nextSmall(n);
26+
stack<int>st;
27+
for(int i=0;i<n;i++)
28+
{
29+
while(!st.empty()&&arr[st.top()]>=arr[i])
30+
{
31+
st.pop();
32+
}
33+
if(!st.empty())
34+
nextSmall[i]=st.top();
35+
else
36+
nextSmall[i]=-1;
37+
st.push(i);
38+
}
39+
return nextSmall;
40+
}
41+
42+
int largestRectangleArea(vector<int>& heights) {
43+
vector<int>nextSmallToLeft=findNextSmallToLeft(heights);
44+
vector<int>nextSmallToRight=findNextSmallToRight(heights);
45+
int largestRectangle=0;
46+
for(int i=0;i<heights.size();i++)
47+
{
48+
int length=nextSmallToRight[i]-nextSmallToLeft[i]-1;
49+
cout<<length<<"\n";
50+
largestRectangle=max(largestRectangle,length*heights[i]);
51+
}
52+
return largestRectangle;
53+
}
54+
};

0 commit comments

Comments
 (0)