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;
    }
};
相关推荐
Coovally AI模型快速验证3 小时前
农田扫描提速37%!基于检测置信度的无人机“智能抽查”路径规划,Coovally一键加速模型落地
深度学习·算法·yolo·计算机视觉·transformer·无人机
pusue_the_sun3 小时前
数据结构:二叉树oj练习
c语言·数据结构·算法·二叉树
RaymondZhao344 小时前
【全面推导】策略梯度算法:公式、偏差方差与进化
人工智能·深度学习·算法·机器学习·chatgpt
zhangfeng11334 小时前
DBSCAN算法详解和参数优化,基于密度的空间聚类算法,特别擅长处理不规则形状的聚类和噪声数据
算法·机器学习·聚类
圣保罗的大教堂5 小时前
leetcode 2348. 全 0 子数组的数目 中等
leetcode
啊阿狸不会拉杆5 小时前
《算法导论》第 32 章 - 字符串匹配
开发语言·c++·算法
小学生的信奥之路5 小时前
洛谷P3817题解:贪心算法解决糖果分配问题
c++·算法·贪心算法
你知道网上冲浪吗6 小时前
【原创理论】Stochastic Coupled Dyadic System (SCDS):一个用于两性关系动力学建模的随机耦合系统框架
python·算法·数学建模·数值分析
地平线开发者7 小时前
征程 6 | PTQ 精度调优辅助代码,总有你用得上的
算法·自动驾驶
Tisfy8 小时前
LeetCode 837.新 21 点:动态规划+滑动窗口
数学·算法·leetcode·动态规划·dp·滑动窗口·概率