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.spa

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].code

 

The largest rectangle is shown in the shaded area, which has area = 10 unit.blog

 

For example,
Given height = [2,1,5,6,2,3],
return 10.

it

思路:若是當前大或者相等,說明有多是新的Rectangle的起點,入棧i++class

        若是當前小,那麼從棧頂彈出來,當作右邊界進行計算面積,這時候不如棧.全部信息都在棧裏面im

 

另一種思路是二分,很好寫。top

 int largestRectArea(vector<int> &h) {
        stack<int> p;
        int i = 0, m = 0;
        h.push_back(0);
        while(i < h.size()) {
            if(p.empty() || h[p.top()] <= h[i])
                p.push(i++);
            else {
                int t = p.top();
                p.pop();
                m = max(m, h[t] * (p.empty() ? i : i - p.top() - 1 ));
            }
        }
        return m;
    }
相關文章
相關標籤/搜索