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;
}
};