Largest Rectangle in Histogram
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.
首先想到一種最直觀的方法:把平面看做大矩陣,條形看做1,非條形看做0,尋找最大全1矩陣。
思路上是正確的,可以用DP來做,不過會超時。
網上看到一種借助棧的做法,代碼很漂亮,但是解釋都非常模糊,我看懂之后,決定仔細描述思路如下:
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
(2)1比2小,不滿足升序條件,因此將2彈出,並記錄當前結果為2*1=2。
將2替換為1重新進棧。s={1,1}, result = 2
(3)5比1大,滿足升序條件,進棧。s={1,1,5},result = 2
(4)6比5大,滿足升序條件,進棧。s={1,1,5,6},result = 2
(5)2比6小,不滿足升序條件,因此將6彈出,並記錄當前結果為6*1=6。s={1,1,5},result = 6
2比5小,不滿足升序條件,因此將5彈出,並記錄當前結果為5*2=10(因為已經彈出的5,6是升序的)。s={1,1},result = 10
2比1大,將彈出的5,6替換為2重新進棧。s={1,1,2,2,2},result = 10
(6)3比2大,滿足升序條件,進棧。s={1,1,2,2,2,3},result = 10
棧構建完成,滿足升序條件,因此按照升序處理辦法得到上述的max(height[i]*(size-i))=max{3*1, 2*2, 2*3, 2*4, 1*5, 1*6}=8<10
綜上所述,result=10
class Solution { public: int largestRectangleArea(vector<int> &height) { int ret = 0; stack<int> stk; for(int i = 0; i < height.size(); i ++) { if(stk.empty() || stk.top() <= height[i]) stk.push(height[i]); else { int count = 0; while(!stk.empty() && stk.top() > height[i]) { count ++; ret = max(ret, stk.top()*count); stk.pop(); } while(count --) stk.push(height[i]); stk.push(height[i]); } } int count = 1; while(!stk.empty()) { ret = max(ret, stk.top()*count); stk.pop(); count ++; } return ret; } };

