题目:84.柱状图中最大的矩形
文章链接:代码随想录
视频链接:LeetCode:84.柱状图中最大的矩形
题目链接:力扣题目链接
图释:


class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        // 输出结果
        int result = 0; 
        stack<int> st;
        heights.insert(heights.begin(), 0); // 数组头部加入元素0
        heights.push_back(0); // 数组结尾加入元素0  为了解决本身数组为递增时,最后一个元素进行截断
        st.push(0);
        // 第一个元素已经入栈,从下标1开始
        for(int i=1; i<heights.size(); i++){
            if(heights[i]>heights[st.top()]){ // 当前元素大于栈口元素,则添加到栈中
                st.push(i);
            }else if(heights[i]==heights[st.top()]){ // 当前元素等于栈口元素,则添加到栈中也可以将栈口元素弹出再加进去
                // st.pop();
                // st.push(i);
                st.push(i);
            }else{
                while(!st.empty() && heights[i]<heights[st.top()]){  // 循环拿出栈中的元素跟当前的元素进行比较,直到当前元素小于等于栈口元素
                    int mid = st.top(); // 中间为栈顶元素,作为高
                    st.pop(); 
                    if(!st.empty()){  // 判断栈内是否还有元素
                        int left = st.top(); //左边的高度
                        int right = i; 
                        int w = right - left -1; 右减左再减1作为宽
                        int h = heights[mid];
                        result = max(result, w*h);
                    }
                }
                st.push(i);
            }
        }
        return result;
    }
};
















![P1450 [HAOI2008] 硬币购物 dp 容斥 —— s - c[i]*(d[i]+1)怎么理解](https://img-blog.csdnimg.cn/direct/827fd5afe0104237bc75fbb688247b0b.png)

