Skip to content

Commit a2c45e9

Browse files
authored
Create 084.Largest-Rectangle-in-Histogram_v1.cpp
1 parent bdaaa31 commit a2c45e9

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
int largestRectangleArea(vector<int>& heights)
4+
{
5+
int n = heights.size();
6+
stack<int>stk;
7+
vector<int>nextSmaller(n, n);
8+
for (int i=0; i<heights.size(); i++)
9+
{
10+
while (!stk.empty() && heights[stk.top()] > heights[i])
11+
{
12+
nextSmaller[stk.top()] = i;
13+
stk.pop();
14+
}
15+
stk.push(i);
16+
}
17+
18+
while (!stk.empty()) stk.pop();
19+
vector<int>prevSmaller(n, -1);
20+
for (int i=0; i<heights.size(); i++)
21+
{
22+
while (!stk.empty() && heights[stk.top()] > heights[i])
23+
{
24+
stk.pop();
25+
}
26+
if (!stk.empty())
27+
prevSmaller[i] = stk.top();
28+
stk.push(i);
29+
}
30+
31+
int ret = 0;
32+
for (int i=0; i<n; i++)
33+
ret = max(ret, heights[i]*(nextSmaller[i] - prevSmaller[i] - 1));
34+
35+
return ret;
36+
}
37+
};

0 commit comments

Comments
 (0)