代码随想录算法训练营第六十天| LeetCode84.柱状图中最大的矩形

84.柱状图中最大的矩形

题目:力扣

class Solution {
public:
    int largestRectangleArea(vector& heights) {
        int result = 0;
        stack s;
        heights.insert(heights.begin(), 0); // 数组头部加入元素0
        heights.push_back(0); // 数组尾部加入元素0
        s.push(0);
        for(int i = 1; i < heights.size(); ++i){
            while(!s.empty() && heights[i]< heights[s.top()]){
                int mid = s.top();
                s.pop();
                int left = s.top();
                int right = i;
                int h = heights[mid];
                int w = right - left - 1;
                result =  max(result, h * w); 
            }
            s.push(i);
        }
        return result;
    }
};

总结

题型:单调栈,和接雨水刚好相反

你可能感兴趣的:(代码随想录算法训练营,算法,leetcode,c++)