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.

[2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area =
10
unit.For example,
Given height =
return
Given height =
[2,1,5,6,2,3]
,return
10
.
int largestRectangleArea(vector<int> &height) { int maxarea = 0, index = 0, n = height.size(); stack<int> s; while(index < n){ if(s.empty() || height[s.top()] <= height[index]) s.push(index++); else{ int topIndex = s.top();s.pop(); int topOfArea = height[topIndex]*(s.empty() ? index : index-s.top()-1); maxarea = max(topOfArea,maxarea); } } while(!s.empty()){ int topIndex = s.top();s.pop(); int topOfArea = height[topIndex]*(s.empty() ? index : index-s.top()-1); maxarea = max(topOfArea,maxarea); } return maxarea; }
关于本题的一点自己的想法
将直方图的最高点连起来就会形成如下图类似的有波谷的曲线

两个波谷之间就是一个局部的凸起的形状(局部直方图构成)
不同凸起之间会有各自的最大直方图面积,相互之间不会影响(底部波谷与波谷除外),
求出每个凸起的面积,取最大值
然后底部波谷之间连线又会构成曲线,求出凸起的面积
直到最后没有凸起,
所求的最大面积即位直方图面积