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
.
题意:给出h数组为宽度为1的矩形柱的高度,求这堆矩形柱中最大的矩形面积。
分析:关键是找到以h[i]为最低的连续矩形的最左和最右位置left[i],right[i],即找到h[i]左边和右边第一个小于h[i]的位置
一般方法:遍历矩形的左右边界,复杂度O(n^2)
O(n)方法:遍历h,若栈为空或h[i]>=栈顶位置的高度,i入栈;否则,一直出栈直到满足h[i]>=栈顶位置的高度
出栈时计算面积,right为i-1,left为栈中的前一个元素(此时的栈顶)+1
遍历后,若栈不为空,依次出栈并计算面积,right为len-1,left同上
原理:由于h[i]>=栈顶位置的高度才压栈,所以出栈时的right一定为当前元素i,即右边第一个小于h[top]的位置
而由于压入i前先把>=h[i]的都出栈,那么栈内一定是高度严格递增的,left即为栈内前一个元素,即左边第一个小于h[top]的位置
注意:h[i]>=栈顶位置的高度入栈,考虑了重复元素的情况,只记录重复元素的最后出现位置
代码:
class Solution { public: int largestRectangleArea(vector<int> &height) { int len = height.size(); stack<int> st; int ans = 0; for(int i=0; i<len; i++) { while(!st.empty() && height[st.top()]>=height[i]) { int curi = st.top(); st.pop(); int now; if(st.empty()) now = height[curi]*i; else now = height[curi]*(i-st.top()-1); if(now>ans) ans = now; } st.push(i); } while(!st.empty()) { int curi = st.top(); st.pop(); int now; if(st.empty()) now = height[curi]*len; else now = height[curi]*(len-st.top()-1); if(now>ans) ans = now; } return ans; } };