LeetCode 84. 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 heights = [2,1,5,6,2,3],
return 10.

 

思路: 单调栈, 这次又错了好几次。 在单调栈的时候多想想是否需要更新,以及重复之类的。

这个主要是考虑替换。

AC代码:

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        vector<int> hs = heights;
        int n = hs.size();
        if(n == 0) return 0;
        hs.push_back(0);
        stack<int>s;
        int ans = 0;
        s.push(0);

        for(int i=1; i<=n; i++)
        {
            int cur = -1;
            while(s.size() && hs[s.top()] >= hs[i])
            {
                cur = s.top();
                s.pop();
                ans = max(ans, (i-cur)*hs[cur]);
            }
            if(cur != -1 && hs[cur]>=hs[i])
            {
                hs[cur] = hs[i];
                s.push(cur);
            }
            else 
            {
                s.push(i);
            }
        }
        return ans;
    }
};

 

posted @ 2016-04-12 21:28  Gu Feiyang  阅读(121)  评论(0)    收藏  举报