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;
    }
}
相关推荐
Zik----20 分钟前
Leetcode27 —— 移除元素(双指针)
数据结构·算法
陆嵩40 分钟前
GMRES 方法的数学推导及其算法表示
算法·概率论·arnoldi·gmres·minres·givens·hessenberg
plus4s1 小时前
2月22日(94-96题)
算法
tankeven1 小时前
HJ98 喜欢切数组的红
c++·算法
adore.9681 小时前
2.22 oj基础92 93 94+U12
数据结构·c++·算法
颜酱2 小时前
前缀和技巧全解析:从基础到进阶
javascript·后端·算法
Rhystt2 小时前
代码随想录第二十六天|669. 修剪二叉搜索树、108.将有序数组转换为二叉搜索树、538.把二叉搜索树转换为累加树
数据结构·c++·算法·leetcode
想做功的洛伦兹力12 小时前
2026/2/22日打卡
数据结构·算法
不染尘.2 小时前
字符串哈希
开发语言·数据结构·c++·算法·哈希算法
今儿敲了吗2 小时前
25| 丢手绢
数据结构·c++·笔记·学习·算法