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 heights = [2,1,5,6,2,3]
,
return 10
.
题意
简单的说就是一个数组表示每个建筑的高度(宽度为1),每个建筑紧挨着。求这些建筑覆盖的最大矩形面积是多少。
题解
暴力方法:每个柱子向左右扩展,遇到比最矮柱还矮的就计算此时面积,然后与原最大面积相比。取最后每个柱子中最大的那个面积。会超时。
用栈的方法,这个方法比较难理解,下面介绍一下整个思路:
1、如果已知height数组是升序的,应该怎么做?
比如1,2,5,7,8
那么就是(1*5) vs. (2*4) vs. (5*3) vs. (7*2) vs. (8*1)
也就是max(height[i]*(size-i))
2、使用栈的目的就是构造这样的升序序列,按照以上方法求解。
但是height本身不一定是升序的,应该怎样构建栈?
比如2,1,5,6,2,3
(1)2进栈。s={2}, result = 0 (实际代码中,栈里存放的是下标i,方便求出size的值。这里为了直观,用值表示)
(2)1比2小,不满足升序条件,因此将2弹出,并记录当前结果为2*1=2。(此时升序只有一个s={2})
2出栈后,最小的1重新进栈。s={1}, result = 2
(3)5比1大,满足升序条件,进栈。s={1,5},result = 2
(4)6比5大,满足升序条件,进栈。s={1,5,6},result = 2
(5)2比6小,不满足升序条件,因此将6弹出,并记录当前结果为6*1=6。这里的size=1用下标值求出
s={1,5},result = 6
2比5小,不满足升序条件,因此将5弹出,并记录当前结果为5*2=10(因为已经弹出的5,6是升序的)。
s={1},result = 10
2比1大,将2进栈。s={1,2},result = 10
(6)3比2大,满足升序条件,进栈。s={1,2,3},result = 10
(7)此时,已经遍历完了。为了继续求出s里面的最大面积,我们自己添加一个height元素0;
这样,像第五步那也循环,求出3*1=3, 2*2=4, 1*6=6(这里需要注意为何是1*6,因为1是s里最后一个元素,所以这个元素是最矮的,所以这个size=i) result=10;
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> stk;
int max_area=0;
heights.push_back(0);
for(int i=0;i<heights.size();)
{
if(stk.empty()||heights[i]>heights[stk.top()])
stk.push(i++);
else
{
int cur_height=heights[stk.top()];
stk.pop();
int size= stk.empty() ? i : i-stk.top()-1;
max_area=max(max_area,cur_height*size);
}
}
return max_area;
}
};