题意: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.
题解:我们用栈来保存直方图中的递增子序列,若i在栈中,则在i之前比i小的直方图的下标肯定也在栈中,在i之后只能放入比height[i]高的下标,因为后面的比它高,所以以height[i]为高的矩形面积还可能增加。
若碰到了比它高度低的直方,则我们知道它的最大矩形也就到头了,所以它的面积就是栈中上一个比它低的直方与当前要入栈的比它低的直方之间的宽度乘以它的高度。
代码如下:
class Solution {
public:
int largestRectangleArea(vector<int>& height) {
height.push_back(0);
int N = height.size();
stack<int> s;
int maxArea = 0;
int i = 0;
/*栈中保持一个递增子序列*/
while(i < N) {
if(s.empty() || height[i] >= height[s.top()]) {
s.push(i++);
}
else {
int j = s.top();
s.pop();
int width = (s.empty()) ? i : i-s.top()-1;
//若为空,表示在i之前height[j]最小
//若不为空,则表示在s.top()与i之间height[j]最小
maxArea = max(maxArea, height[j]*width);
}
}
return maxArea;
}
};