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
.
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int max_area = ;
stack<int> s;
height.push_back();
int i = ;
while (i < height.size()) {
if (s.empty() || height[s.top()] < height[i]) {
s.push(i++);
} else {
int t = s.top();
s.pop();
max_area = max(max_area,
height[t] * (s.empty() ? i : i - s.top() - ));
}
}
return max_area;
}
};
O(n2)的算法还是很好想的,但是如果借用数据结构--栈,可以使复杂度降低。
从左向右扫描数组,如果bar递增,则入栈,遇到第一个下降的bar时,开始出栈,计算从该bar(不含)到栈顶元素(含)之间形成的矩形面积,直到遇到栈里第一个低于它的bar,此时可以继续向前扫描下一个元素。
栈里维护的是递增序列。