Skip to content

Commit

Permalink
Create 084.Largest-Rectangle-in-Histogram_v1.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Jul 9, 2022
1 parent bdaaa31 commit a2c45e9
Showing 1 changed file with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Solution {
public:
int largestRectangleArea(vector<int>& heights)
{
int n = heights.size();
stack<int>stk;
vector<int>nextSmaller(n, n);
for (int i=0; i<heights.size(); i++)
{
while (!stk.empty() && heights[stk.top()] > heights[i])
{
nextSmaller[stk.top()] = i;
stk.pop();
}
stk.push(i);
}

while (!stk.empty()) stk.pop();
vector<int>prevSmaller(n, -1);
for (int i=0; i<heights.size(); i++)
{
while (!stk.empty() && heights[stk.top()] > heights[i])
{
stk.pop();
}
if (!stk.empty())
prevSmaller[i] = stk.top();
stk.push(i);
}

int ret = 0;
for (int i=0; i<n; i++)
ret = max(ret, heights[i]*(nextSmaller[i] - prevSmaller[i] - 1));

return ret;
}
};

0 comments on commit a2c45e9

Please sign in to comment.