[Question]
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 =
return
Given height =
[2,1,5,6,2,3]
,return
10
.
[Analysis]
If we can calculate each rectangle with max height of H[i], we can get the maximum area. To calculate such rectangles, for each H[i], we need to get the first H[j] where H[j]<H[i], j<i and the first H[k]<H[i], where k>i.
If we can calculate each rectangle with max height of H[i], we can get the maximum area. To calculate such rectangles, for each H[i], we need to get the first H[j] where H[j]<H[i], j<i and the first H[k]<H[i], where k>i.
Using a stack can help to find such j and k. The Time Complexity is O(N).
[Solution]class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
stack<int> st;
int area=0;
heights.push_back(0);
for(int i=0; i<heights.size(); i++) {
while(!st.empty() && heights[st.top()]>heights[i] ) {
int h = heights[st.top()];
st.pop();
int j=st.empty()?-1:st.top();
area = max(area, (i-j-1)* h);
}
//--this loop is not necessary but save calculation above.
while (!st.empty() && heights[st.top()]==heights[i])
st.pop();
st.push(i);
}
return area;
}
};
No comments:
Post a Comment