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.
Solution
This problem is really hard for me, so I came to Discuss
and found most methods are based on stack.
If there is a largest rectangle, position from s
to e
, there must be i
between s
and e
, the height of i
is the smallest in height[s:e], and height[s-1], height[e+1] must lower than height[i].
so, for each height[n], n=0,1,…,height.size()-1. calculate when height[n] is the smallest between height[s:e] and find out s
e
.
Below is cpp code.
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int res(0);
height.push_back(0);
vector<int> index;
int cur_height(0);
int cur_index(0);
for(int i = 0; i < height.size(); ++i){
while(!index.empty() && height[index.back()] >= height[i]){
cur_height = height[index.back()];
index.pop_back();
cur_index = index.empty()? -1:index.back();
res = max(res, cur_height * (i - cur_index - 1));
}
index.push_back(i);
}
return res;
}
};
i is e
and cur_index is s
the height is ‘cur_height’