一. Largest Rectangle in Histogram
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 heights = [2,1,5,6,2,3],
return 10.
Difficulty:Hard
TIME:TIMEOUT
解法
这道题如果采用 O(n2) 的做法,当然是极其简单的,不过显然会超时。
假设是一个增序列比如<1,2,3,4,5>,由于右边的数都要比左边大,因此如果以左边的数作为边是完全可行的。但我们知道左边的下标,但还是不确定右边的下标,因为没有出现一个小于栈顶的数。如果序列变成了<1,2,3,4,5,3>,这个时候就开始计算最大值了,从5开始,到4:
- 对于5来说,长方形面积为5 * 1 = 5
- 对于4来说,长方形面积为4 * 2 = 8
序列这个时候变成了<1,2,3,3>,也就是说比3大的数都计算完成。继续添加其余的数。
int largestRectangleArea(vector<int>& heights) {
if(heights.empty())
return 0;
heights.push_back(0); //后导0用来清空栈
int result = 0;
vector<int> v;
for(int i = 0; i < heights.size(); i++) {
while(!v.empty() && heights[i] < heights[v.back()]) {
int h = heights[v.back()];
v.pop_back();
int k = v.empty() ? -1 : v.back(); //注意这里是用前一个数的下标来计算的
result = max((i - k - 1) * h, result); //计算面积
}
v.push_back(i);
}
return result;
}
代码的时间复杂度为 O(n) 。