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

柱状图中最大的矩形

题目链接:84. 柱状图中最大的矩形 - 力扣(LeetCode)

思路:掌握了……吗?还是参考了下官网思路。代码随想录 (programmercarl.com)

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

        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);
            }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;
                        result=max(result,w*heights[mid]);
                    }
                }
                st.push(i);
            }
        }
        return result;
    }
};

 

🥳🥳🥳结束啦😁😁😁

posted @   SandaiYoung  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示