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;        
    }
};



原创文章 39 获赞 5 访问量 4923

猜你喜欢

转载自blog.csdn.net/q1072118803/article/details/105201597