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;
    }
};
相关推荐
2301_7944615722 分钟前
力扣-283-移动零
算法·leetcode·职场和发展
编程绿豆侠23 分钟前
力扣HOT100之二叉树:98. 验证二叉搜索树
算法·leetcode·职场和发展
技术流浪者38 分钟前
C/C++实践(十)C语言冒泡排序深度解析:发展历史、技术方法与应用场景
c语言·数据结构·c++·算法·排序算法
I AM_SUN1 小时前
98. 验证二叉搜索树
数据结构·c++·算法·leetcode
学习中的码虫2 小时前
数据结构基础排序算法
数据结构·算法·排序算法
_安晓2 小时前
数据结构 -- 顺序查找和折半查找
数据结构
yidaqiqi2 小时前
[目标检测] YOLO系列算法讲解
算法·yolo·目标检测
飞天狗1112 小时前
2024 山东省ccpc省赛
c++·算法
代码不停2 小时前
Java二叉树题目练习
java·开发语言·数据结构
卡尔曼的BD SLAMer3 小时前
计算机视觉与深度学习 | Python实现EMD-SSA-VMD-LSTM-Attention时间序列预测(完整源码和数据)
python·深度学习·算法·cnn·lstm