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;
    }
};
相关推荐
Flower#1 小时前
【算法】树上启发式合并 (CCPC2020长春 F. Strange Memory)
c++·算法
Asmalin2 小时前
【代码随想录day 35】 力扣 1049. 最后一块石头的重量 II
算法·leetcode
Asmalin2 小时前
【代码随想录day 35】 力扣 494. 目标和
算法·leetcode·职场和发展
Miraitowa_cheems2 小时前
LeetCode算法日记 - Day 63: 图像渲染、岛屿数量
java·数据结构·算法·leetcode·决策树·贪心算法·深度优先
·云扬·2 小时前
【Leetcode hot 100】51.N皇后
linux·算法·leetcode
橘颂TA2 小时前
【剑斩OFFER】算法的暴力美学——将 x 减到零的最小操作数
c++·算法·leetcode·动态规划
拾光Ծ3 小时前
【数据结构】二叉搜索树 C++ 简单实现:增删查改全攻略
数据结构·c++·算法
小贾要学习3 小时前
编程中常见的排序算法
数据结构·c++·算法·排序算法
Yupureki3 小时前
从零开始的C++学习生活 4:类和对象(下)
c语言·数据结构·c++·学习
还有几根头发呀3 小时前
[特殊字符] LeetCode 143 重排链表(Reorder List)详解
数据结构·链表