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.spa
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.code
The largest rectangle is shown in the shaded area, which has area = 10
unit.blog
For example,
Given height = [2,1,5,6,2,3]
,
return 10
.
it
思路:若是当前大或者相等,说明有多是新的Rectangle的起点,入栈i++class
若是当前小,那么从栈顶弹出来,当作右边界进行计算面积,这时候不如栈.全部信息都在栈里面im
另一种思路是二分,很好写。top
int largestRectArea(vector<int> &h) { stack<int> p; int i = 0, m = 0; h.push_back(0); while(i < h.size()) { if(p.empty() || h[p.top()] <= h[i]) p.push(i++); else { int t = p.top(); p.pop(); m = max(m, h[t] * (p.empty() ? i : i - p.top() - 1 )); } } return m; }