Description
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.
Example:
Input: [2,1,5,6,2,3]
Output: 10
分析
题目的意思是:给你一个柱形图数组,求能够围成的最大的矩形。
- 栈存储的是下标,维护的是递增序列,如果不递增,则出栈计算长度。
- 用栈计算每一块板能延伸到的左右边界 ,对每一块板;栈顶矮,这一块左边界确定,入栈;堆栈顶高,栈顶右边界确定,出栈,计算面积
- 入栈时左边界确定,出栈时右边界确定,栈里元素是递增的。
- 时间复杂度 O(n),leetcode hard难度。
代码
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.push_back(-1);
stack<int> s;
int index=0;
int sum=0;
while(index<heights.size()){
if(s.size()==0||heights[s.top()]<=heights[index]){
s.push(index);
index++;
}else{
int base=s.top();
s.pop();
int max_area=0;
if(s.size()==0){
max_area=heights[base]*index;
}else{
max_area=heights[base]*(index-1-s.top());
}
if(sum<max_area){
sum=max_area;
}
}
}
return sum;
}
};
参考文献
[编程题]largest-rectangle-in-histogram
leetcode之Largest Rectangle in Histogram