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
.
一个栈,栈底的元素小于栈顶,每次压入新元素之前弹出所有大于新元素的就元素
所有点进栈一次,出栈时确认该点为最小值的作用域(起点为栈内上一个元素下标的后一位,终点为当前压入元素下标前一位) 复杂度O(n)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Solution { public: int largestRectangleArea(vector<int> &height) { if(height.size()==0)return 0; stack<pair<int,int> > sta; pair<int,int> p,q; int max=0; int start,end,area; for(int i=0;i<height.size();i++){ p.first=height[i]; p.second=i; if(sta.size()==0){ sta.push(p); } else{ while(sta.top().first>p.first){ q=sta.top(); sta.pop(); end=i-1; if(sta.size()==0){ start=0; area=q.first*(end-start+1); if(area>max)max=area; break; } else{ start=sta.top().second+1; area=q.first*(end-start+1); if(area>max)max=area; } } if(sta.size()!=0){ if(sta.top().first==p.first){ sta.top().second=i; } else{ sta.push(p); } } else{ sta.push(p); } } } end=height.size()-1; while(sta.size()!=0){ q=sta.top(); sta.pop(); if(sta.size()==0){ start=0; area=q.first*(end-start+1); if(area>max)max=area; } else{ start=sta.top().second+1; area=q.first*(end-start+1); if(area>max)max=area; } } return max; } };