Skip to content

Commit 0daf1a4

Browse files
committed
Time: 208 ms (53.09%), Space: 81.4 MB (55.79%) - LeetHub
1 parent 5133d67 commit 0daf1a4

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
class Solution {
2+
public:
3+
int largestRectangleArea(vector<int>& heights) {
4+
5+
int n = heights.size();
6+
7+
vector<int> leftSmall(n), rightSmall(n);
8+
9+
stack<int> st;
10+
11+
for(int i = 0; i < n; ++i)
12+
{
13+
if(st.empty())
14+
{
15+
st.push(i);
16+
leftSmall[i] = 0;
17+
}
18+
else if(heights[st.top()] >= heights[i])
19+
{
20+
while(!st.empty() and heights[st.top()] >= heights[i])
21+
st.pop();
22+
23+
if(st.empty())
24+
leftSmall[i] = 0;
25+
else
26+
leftSmall[i] = st.top() +1;
27+
st.push(i);
28+
}
29+
else
30+
{
31+
leftSmall[i] = st.top() + 1;
32+
st.push(i);
33+
}
34+
}
35+
36+
// for(auto itr : leftSmall)
37+
// cout<<itr<<" ";
38+
// cout<<endl;
39+
40+
while(!st.empty())
41+
st.pop();
42+
43+
for(int i = n-1; i >= 0; --i)
44+
{
45+
if(st.empty())
46+
{
47+
st.push(i);
48+
rightSmall[i] = n-1;
49+
}
50+
else if(heights[st.top()] >= heights[i])
51+
{
52+
while(!st.empty() and heights[st.top()] >= heights[i])
53+
st.pop();
54+
if(st.empty())
55+
rightSmall[i] = n-1;
56+
else
57+
rightSmall[i] = st.top() - 1;
58+
st.push(i);
59+
}
60+
else{
61+
rightSmall[i] = st.top() - 1;
62+
st.push(i);
63+
}
64+
}
65+
66+
67+
// for(auto itr : rightSmall)
68+
// cout<<itr<<" ";
69+
// cout<<endl;
70+
71+
int ans = 0;
72+
73+
for(int i =0 ; i<n; ++i)
74+
{
75+
ans = max(ans, heights[i] * (rightSmall[i] - leftSmall[i] + 1));
76+
// cout<<ans<<endl;
77+
}
78+
79+
return ans;
80+
81+
}
82+
};

0 commit comments

Comments
 (0)