Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
题意是:给一个连续的非负整数数组,求出该数组的直方图所能组成的面积最大的长方形。如图所示
这里解决思路就是维护一个栈s,如果栈顶的元素大于要push的元素,则直接推进来,否则就需要对栈不停地pop,同时更新result=max(result,count*s.top()), 直到栈顶的元素小于等于要push的元素。因为每次push的元素若大于栈顶的元素,后面栈pop可以直接计算到。若小于,则先计算栈里面所能组成的最大面积。
class Solution {
public:
int largestRectangleArea(vector<int>& heights)
{
int re=0;
stack<int> s;
for(int i=0;i<heights.size();i++)
{
//当栈为空的时候,直接push
if(s.empty())
{
s.push(heights[i]);
}
//当栈顶元素小于当前元素,直接push
else if(s.top()<=heights[i])
{
s.push(heights[i]);
}
//当栈顶元素大于当前元素,需要对当前栈进行计算,同时重新push count个当前元素,count为pop的数量。
else if(s.top()>heights[i])
{
int count=0;
while(s.empty()==false&&s.top()>heights[i])
{
count++;
re=max(re,count*s.top());
s.pop();
}
for(int j=0;j<=count;j++)
{
s.push(heights[i]);
}
}
}
int count=0;
while(s.empty()==false)
{
count++;
re=max(re,count*s.top());
s.pop();
}
return re;
}
};