单调栈-LeetCode 84. 柱状图中最大的矩形

LeetCode 84. 柱状图中最大的矩形

运用递增单调栈,求取最小值的右区间

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        if(heights.size() <= 0) return 0;
        int maxArea = 0;
        stack<int> s;
        s.push(0);
        heights.push_back(0);
        for(int i=1;i<heights.size();i++){
            while(!s.empty() && heights[s.top()] > heights[i]){
                int cur = s.top();
                s.pop();
                maxArea = max(maxArea,heights[cur]*(s.empty()? i:i-s.top()-1));
            }
            s.push(i);
        }
        return maxArea;
    }
};
原文地址:https://www.cnblogs.com/--zz/p/11218618.html