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) {
stack<int> st;
int max = 0;
for (int i = 0; i < height.size(); ++i) {
if (st.empty()) {
st.push(i);
} else if (height[i] > height[st.top()]){
st.push(i);
} else if (height[i] < height[st.top()]) {
while(!st.empty() && height[i] < height[st.top()]) {
int h = height[st.top()];
st.pop();
if (st.empty()) {
max = max < h*i ? h*i : max;
} else {
max = max < h*(i-st.top()-1) ? h*(i-st.top()-1) : max;
}
}
st.push(i);
} else { // ==
st.pop();
st.push(i);
}
}
int r = height.size()-1;
for (int i = st.size()-1; i >= 0; --i) {
int h = height[st.top()];
st.pop();
if (st.empty()) {
max = max < h*(r+1) ? h*(r+1) : max;
} else {
max = max < h*(r-st.top()) ? h*(r-st.top()) : max;
}
}
return max;
}
};