LeetCode84.柱状图中最大矩形

cpp 复制代码
class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int size = heights.size();
        int n = heights.size();
        vector<int> left(size, -1);
        stack<int> st;
        st.push(0);
        //找到每个柱子左侧小于它高度的最近元素的下标
        for(int i = 1; i < size; i++){
            while(!st.empty() && heights[st.top()] >= heights[i])
                st.pop();
            if(!st.empty())
                left[i] = st.top();
            st.push(i);
        }
        vector<int> right(size, n);
        stack<int> st2;
        st2.push(n - 1);
        //找到每个柱子左侧小于它高度的最近元素的下标
        for(int i = n - 2; i >= 0; i--){
            while(!st2.empty() && heights[st2.top()] >= heights[i])
                st2.pop();
            if(!st2.empty())
                right[i] = st2.top();
            st2.push(i);
        }
        int res = 0;
        for(int i = 0; i < size; i++){
            res = max(res, heights[i] * (right[i] - left[i] - 1));
        }
        return res;
    }
};
相关推荐
CoovallyAIHub29 分钟前
首个大规模、跨模态医学影像编辑数据集,Med-Banana-50K数据集专为医学AI打造(附数据集地址)
深度学习·算法·计算机视觉
熬了夜的程序员30 分钟前
【LeetCode】101. 对称二叉树
算法·leetcode·链表·职场和发展·矩阵
却道天凉_好个秋1 小时前
目标检测算法与原理(二):Tensorflow实现迁移学习
算法·目标检测·tensorflow
柳鲲鹏2 小时前
RGB转换为NV12,查表式算法
linux·c语言·算法
橘颂TA2 小时前
【剑斩OFFER】算法的暴力美学——串联所有单词的字串
数据结构·算法·c/c++
Kuo-Teng2 小时前
LeetCode 73: Set Matrix Zeroes
java·算法·leetcode·职场和发展
mit6.8242 小时前
[HDiffPatch] 补丁算法 | `patch_decompress_with_cache` | `getStreamClip` | RLE游程编码
c++·算法
程序猿20232 小时前
Python每日一练---第六天:罗马数字转整数
开发语言·python·算法
葵续浅笑2 小时前
LeetCode - 杨辉三角 / 二叉树的最大深度
java·数据结构·算法·leetcode