84. 柱状图中最大的矩形

84. 柱状图中最大的矩形

双指针

java 复制代码
class Solution {
    public int largestRectangleArea(int[] heights) {
        int n = heights.length;
        int[] minLeftIndex = new int[n];
        int[] minRightIndex = new int[n];

        minLeftIndex[0] = -1;
        for(int i = 1; i < n; i++){
            int t = i - 1;
            while(t >= 0 && heights[t] >= heights[i]) t = minLeftIndex[t];
            minLeftIndex[i] = t;
        }

        minRightIndex[n - 1] = n;
        for(int i = n - 2; i >= 0; i--){
            int t = i + 1;
            while(t < n && heights[t] >= heights[i]) t = minRightIndex[t];
            minRightIndex[i] = t;
        }

        int res = 0, sum = 0;
        for(int i = 0; i < n; i++){
            sum = heights[i] * (minRightIndex[i] - minLeftIndex[i] - 1);
            res = Math.max(res, sum);
        }

        return res;
    }
}

单调栈

java 复制代码
class Solution {
    public int largestRectangleArea(int[] heights) {
        int len = heights.length + 2;
        int[] newHeight = new int[len];
        for(int i = 1; i < len - 1; i++) newHeight[i] = heights[i - 1];

        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(0);

        int res = 0;
        for(int i = 1; i < len; i++){
            while(!stack.isEmpty() && newHeight[i] < newHeight[stack.peek()]){
                int mid = stack.pop();
                int h = newHeight[mid];
                int w = i - stack.peek() - 1;
                res = Math.max(res, h * w);
            }
            stack.push(i);
        }

        return res;
    }
}
相关推荐
橘颂TA5 分钟前
【剑斩OFFER】哈希表简介
数据结构·算法·散列表
小尧嵌入式6 分钟前
c++红黑树及B树B+树
开发语言·数据结构·c++·windows·b树·算法·排序算法
tobias.b11 分钟前
408真题解析-2009-10-数据结构-排序
数据结构·算法·排序算法·408考研·408真题·真题解析
Zachary_zlc15 分钟前
有向无环图检测算法和关键路径算法
算法
你撅嘴真丑16 分钟前
素数回文数的个数 与 求分数序列和
算法
Wuliwuliii24 分钟前
贡献延迟计算DP
数据结构·c++·算法·动态规划·dp
ysn1111128 分钟前
简单多边形三角剖分---耳切法(含源码)
算法
e疗AI产品之路29 分钟前
一文介绍Philips DXL心电图算法
算法·pan-tompkins·心电分析
小袁顶风作案38 分钟前
leetcode力扣——135.分发糖果
算法·leetcode·职场和发展