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;
    }
}
相关推荐
好学且牛逼的马7 分钟前
【Hot100|15-LeetCode 238. 除自身以外数组的乘积】
数据结构·算法·leetcode
Tisfy18 分钟前
LeetCode 3651.带传送的最小路径成本:动态规划
算法·leetcode·动态规划·题解·排序
努力学习的小廉21 分钟前
我爱学算法之—— 递归回溯综合(一)
算法·深度优先
m0_7369191021 分钟前
C++中的策略模式实战
开发语言·c++·算法
孞㐑¥22 分钟前
算法—位运算
c++·经验分享·笔记·算法
软件算法开发29 分钟前
基于卷尾猴优化的LSTM深度学习网络模型(CSA-LSTM)的一维时间序列预测算法matlab仿真
深度学习·算法·matlab·lstm·一维时间序列预测·卷尾猴优化·csa-lstm
高洁0136 分钟前
知识图谱如何在制造业实际落地应用
深度学习·算法·机器学习·数据挖掘·知识图谱
BHXDML39 分钟前
数据结构:(二)逻辑之门——栈与队列
java·数据结构·算法
晚风吹长发1 小时前
初步了解Linux中的信号捕捉
linux·运维·服务器·c++·算法·进程·x信号
机器学习之心1 小时前
MATLAB基于GA-ELM与NSGA-Ⅱ算法的42CrMo表面激光熔覆参数多目标优化
算法·matlab·ga-elm