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;
    }
};
相关推荐
music&movie1 小时前
算法工程师认知水平要求总结
人工智能·算法
laocui12 小时前
Σ∆ 数字滤波
人工智能·算法
yzx9910132 小时前
Linux 系统中的算法技巧与性能优化
linux·算法·性能优化
全栈凯哥3 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥3 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu3 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
Humbunklung3 小时前
机器学习算法分类
算法·机器学习·分类
Ai多利3 小时前
深度学习登上Nature子刊!特征选择创新思路
人工智能·算法·计算机视觉·多模态·特征选择
lyh13443 小时前
【SpringBoot自动化部署方法】
数据结构
蒟蒻小袁4 小时前
力扣面试150题--被围绕的区域
leetcode·面试·深度优先