題目描述:
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.
Example:
input: [2,1,5,6,2,3]
Output: 10
解題思路:
本題要求我們求出直方圖中最大的矩形面積。仔細觀察分析可以知道,關鍵是找到直方圖中最大矩形的長和高。
那麼如何得到直方圖中最大矩形呢?一個想法是對於直方圖中的每一個局部峯值,都向前遍歷,算出其最大的公共矩形。
而爲了尋找直方圖中的局部峯值,我們可以藉由stack來實現:即將直方圖的高度依次入棧,只要當前高度小於棧頂,則棧頂爲一個局部峯值。
解法如下:
int largestRectangleArea(vector<int>& heights) {
stack<int> s;
//insert 0 in origial stack
s.push(0);
int res = 0;
for(int i = 0; i < heights.size();){
//if current height larger than s.top,
//push into stack
if(s.empty()||heights[i]>=heights[s.top()]){
s.push(i);
i++;
}
else{
//else, find the current largest rectangle
int h = heights[s.top()];
s.pop();
int w = (!s.empty())?i-s.top()-1:i;
res = max(res,h*w);
}
}
return res;
}