Online Judge Solutions

Thursday, December 25, 2014

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 height = [2,1,5,6,2,3],
return 10.
 
// http://www.ninechapter.com/solutions/largest-rectangle-in-histogram/
class Solution {
public:
   int largestRectangleArea(vector<int> &height) {
       int n = height.size();
       stack<int> st;
       
       int maxArea = 0;
       for(int i = 0;i <= n;i++) {
           int curHeight = i == n? -1 : height[i];
           while (!st.empty() && curHeight <= height[st.top()]) {
               int H = height[st.top()];
               st.pop();
               int W = st.empty() ? i : i - (st.top()+1);
               maxArea = max(maxArea, H*W);
           }
           st.push(i);
       }
       return maxArea;
    }
};

No comments:

Post a Comment