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;
    }
}
相关推荐
iAkuya1 分钟前
(leetcode)力扣100 58组合总和(回溯)
算法·leetcode·职场和发展
80530单词突击赢2 分钟前
C++关联容器深度解析:set/map全攻略
java·数据结构·算法
m0_561359673 分钟前
代码热更新技术
开发语言·c++·算法
xu_yule29 分钟前
算法基础—组合数学
c++·算法
爱尔兰极光30 分钟前
LeetCode--移除元素
算法·leetcode·职场和发展
Tansmjs42 分钟前
C++中的工厂模式变体
开发语言·c++·算法
naruto_lnq43 分钟前
多平台UI框架C++开发
开发语言·c++·算法
Tingjct1 小时前
十大排序算法——交换排序(一)
c语言·开发语言·数据结构·算法·排序算法
MM_MS1 小时前
Halcon图像点运算、获取直方图、直方图均衡化
图像处理·人工智能·算法·目标检测·计算机视觉·c#·视觉检测
每天要多喝水1 小时前
贪心算法专题Day22
算法·贪心算法