leetcode-084 柱狀圖中的最大矩形 單調棧

單調棧

第一次聽說這種方法,很巧妙。
在這裏插入圖片描述
思路轉載自:
作者:6westboy9
鏈接:https://leetcode-cn.com/problems/largest-rectangle-in-histogram/solution/084zhu-zhuang-tu-zhong-zui-da-de-ju-xing-by-6westb/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        stack<int> s;
        s.push(-1);
        int maxArea = 0;
        for(int i=0;i<heights.size();i++)
        {
            while(s.top()!=-1 && heights[i]<heights[s.top()])
            {
                int top = s.top();
                s.pop();
                maxArea = max(heights[top]*(i-s.top()-1),maxArea);
            }
            s.push(i);
        }
        while(s.top()!=-1)
        {
            int top  = s.top();
            s.pop();
            if(heights[top]*(heights.size()-s.top()-1)>maxArea)
                maxArea = heights[top]*(heights.size()-s.top()-1);
        }
        return maxArea;        
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章