单调栈Day36:接雨水

42. 接雨水

利用单调栈先找到左侧第一个大于当前高度的,再用栈的单调特性,弹出的下一个一定大于当前的

就找到了左右的支柱,左右最短的减去当前块高度为h,下标差为w,相乘即为当前块能盛水的面积

cpp 复制代码
    int trap(vector<int>& height) {
        if(height.size() == 0){
            return 0;
        }
        int sum = 0;
        stack<int> st;
        st.push(0);
        for(int i = 1; i < height.size(); i++){
            if(height[i] > height[st.top()]){
                while(!st.empty() && height[i] > height[st.top()]){
                    int mid = st.top();
                    st.pop();
                    if(!st.empty()){
                        int width = i - st.top() - 1;
                        int h = min(height[i], height[st.top()]) - height[mid];
                        sum += width * h;
                    }
                }
            }
            st.push(i);
        }
        return sum;
    }

84. 柱状图中最大的矩形

单调栈(区别接雨水的栈),找每个柱的「左右第一个更矮柱」,中间部分就是能容纳高度为heightmid的矩形,宽度就为两侧矮柱横坐标之差

首尾插 0 是关键技巧,避免栈空 / 边界漏算;

核心计算:弹出柱为高,左右边界间距为宽,取面积最大值。

cpp 复制代码
    int largestRectangleArea(vector<int>& heights) {
        if(heights.size() == 0){
            return 0;
        }
        stack<int> st;
        //首尾插入0
        heights.insert(heights.begin(), 0);
        heights.push_back(0);

        st.push(0);
        int res = 0;
        for(int i = 1; i < heights.size(); i++){
            if(heights[i] < heights[st.top()]){
                while(!st.empty() && heights[i] < heights[st.top()]){
                    int mid = st.top();
                    st.pop();
                    if(!st.empty()) {
                        int h = heights[mid];
                        int w = i - st.top() - 1;
                        res = max(res, h*w);
                    }
                }
            }
            st.push(i);
        }
        return res;
    }
相关推荐
Hillain21 小时前
软件设计师设计模式
java·开发语言·经验分享·笔记·算法·设计模式·软考
战族狼魂21 小时前
AI 量化交易完整学习路线(从零到实战)
人工智能·算法·chatgpt·大语言模型·ai提示词·ai工程化
Frostnova丶1 天前
【算法笔记】数学知识
笔记·算法
吴可可1231 天前
AutoCAD 2016与2014二次开发关键差异
算法
雨白1 天前
哈希:以时间换空间的算法实战
算法
San813_LDD1 天前
[数据结构]LeetCode学习
数据结构·算法·图论
x138702859571 天前
c语言排雷游戏(基础版9*9)
c语言·算法·游戏
sheeta19981 天前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油1 天前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs