[LeetCode] 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.



class Solution {
public:
    int largestRectangleArea(vector<int> &height) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> h;
        vector<int> w;
        int maxArea=0;
        //keep a non-decreasing-height stack
        for(int i=0;i<=height.size();i++)
        {
            //if the stack is empty or current bin is larger than the end of the stack, just push back new element
            int newheight=0;
            if(i<height.size())
                newheight=height[i];
            else
                newheight=-1; //for the case that the last height is larger than the stop of stack and evaluate maxArea
                
            if(h.size()==0 || h[h.size()-1] < newheight)
            {
                h.push_back(newheight);
                w.push_back(1);
                //maxArea=max(maxArea,thisArea);
                continue;
            }
            
            //the case for h[size()-1] >= height[i], search backward for the first height smaller than this bin, evaluate the maximum area the previous bins can get. 
            int j=h.size()-1;
            int minH=INT_MAX;
            int width=0;
            while(j>=0 && h[j] >= newheight)
            {
                minH=min(minH,h[j]);
                width+=w[j];
                maxArea=max(maxArea,minH*width);
                h.pop_back();
                w.pop_back();
                j--;
            }
            w.push_back(width+1);
            h.push_back(newheight);
        }
        return maxArea;
    }
};


你可能感兴趣的:([LeetCode] Largest Rectangle in Histogram)