Wednesday, September 24, 2014

Largest Rectangle in Histogram

//by anniekim
// Keep a non-descending stack. O(n).
to help understanding, a picture in http://fisherlei.blogspot.com/2012/12/leetcode-largest-rectangle-in-histogram.html?spref=bl

    int largestRectangleArea(vector<int> &height) {
        height.push_back(0);
        stack<int> aStack;
        int res=0, i=0, N=height.size();
        while(i<N){
            if(aStack.empty()||height[aStack.top()]<=height[i])
                aStack.push(i++);
            else{//compute the area of  rectangle that column index can cover
                int index=aStack.top();aStack.pop();
                int width=aStack.empty()?i:i-aStack.top()-1;
                res=max(res,width*height[index]);
            }   
        }
        return res;
    }

No comments:

Post a Comment