LeetCode84_柱状图中最大的矩形_单调栈

视频讲解:【LeetCode84_柱状图中最大的矩形_单调栈】 https://www.bilibili.com/video/BV1gg411Q71Z?share_source=copy_web&vd_source=a1d10c96be67b4b38a41d23ddbab3cc1

class Solution {
    public int largestRectangleArea(int[] heights) {
        int result = 0;
        int[] newHeights = new int[heights.length + 2];
        int length = newHeights.length;
        // 左边的0主要是为了得到高度应有的宽度
        newHeights[0] = 0;
        // 右边的0主要是为了破坏单调递增栈的单调性
        newHeights[length - 1] = 0;
        System.arraycopy(heights, 0, newHeights, 1, heights.length);
        Deque<Integer> stack = new LinkedList<>();
        // 放入左边的0的索引
        stack.push(0);
        for (int i = 1; i < length; i++) {
            while (!stack.isEmpty() && newHeights[i] < newHeights[stack.peek()]) {
            	// 破坏单调递增栈,对最大矩形面积做更新
                int currentHeight = newHeights[stack.pop()];
                // stack.peek()表示上一个比当前高度小的值的索引
                int width = i - stack.peek() - 1;
                result = Math.max(result, currentHeight * width);
            }
            // 两种含义
            // 1,维护当前单调递增栈
            // 2,建立新的单调递增栈
            stack.push(i);
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值