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.
可以参看 http://www.cnblogs.com/felixfang/p/3676193.html
想了半天,也想不出来O(n)的解法,于是上网google了一下。
如下图所示,从左到右处理直方,i=4时,小于当前栈顶(及直方3),于是在统计完区间[2,3]的最大值以后,消除掉阴影部分,然后把红线部分作为一个大直方插入。因为,无论后面还是前面的直方,都不可能得到比目前栈顶元素更高的高度了。
class Solution {
public:
/**
* @param height: A list of integer
* @return: The area of largest rectangle in the histogram
*/
int largestRectangleArea(vector<int> &height) {
// write your code here
stack<int> S;
height.push_back(0);
int sum = 0;
for (int i = 0; i < height.size(); i++) {
if (S.empty() || height[i] > height[S.top()]) S.push(i);
else {
int tmp = S.top();
S.pop();
sum = max(sum, height[tmp]*(S.empty()? i : i-S.top()-1));
i--;
}
}
return sum;
}
};