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.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.
For example,
Given height = [2,1,5,6,2,3]
,
return 10
.
分析:可维护一个递增的栈,比较当前元素和栈顶元素的大小,若当前元素较小,继续入栈;否则,出栈,直至栈顶元素小于当前元素。每次出栈,都需要计算面积并与最大面积比较。需要注意的点有:
- 站内维护的是输入高度数组height的索引
- height末尾压入0,以便最后站内元素全部出栈
- 每次元素出栈时,面积的计算不包括当前元素
int largestRectangleArea(vector<int>& height) {
stack<int> s;
height.push_back(0);
int res=0;
for(int i=0;i<height.size();)
{
if(s.empty()||height[i]>=height[s.top()])
s.push(i++);
else
{
int tmp=s.top();s.pop();
res=max(res,height[tmp]*(s.empty()?i:(i-s.top()-1)));
}
}
return res;
}