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
.
这道题,第一眼看去,直观思路是对于每一根柱子,左右扩展,但是这样O(n^2) 超时
对于一根柱子,保存其左侧所有比其高度要高的柱子,那么就可以知道以这根柱子为右边界的面积
实际上这里只需要保存左侧可以匹配的高度以及其下标即可
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int maxArea = 0;
if(height.size() == 0) return 0;
stack<int> hStack;
stack<int> iStack;
for(int i = 0; i < height.size(); i++) {
if(hStack.empty() || height[i] > hStack.top()) {
hStack.push(height[i]);
iStack.push(i);
}
else if(height[i] < hStack.top()) {
int lastIndex = 0;
while(!hStack.empty() && height[i] < hStack.top()) {
lastIndex = iStack.top();
iStack.pop();
int tmpHeight = hStack.top();
hStack.pop();
int tmpArea = tmpHeight*(i - lastIndex);
if(tmpArea > maxArea) maxArea = tmpArea;
}
hStack.push(height[i]);
iStack.push(lastIndex);
}
}
while(!hStack.empty()) {
int tmpArea = hStack.top()*(height.size() - iStack.top());
hStack.pop();
iStack.pop();
if(tmpArea > maxArea) maxArea = tmpArea;
}
return maxArea;
}
};