leetcode84柱状图中最大的矩形

该代码片段是LeetCode中的一个解决方案,使用栈数据结构计算给定高度数组中最大的矩形面积。通过不断比较当前高度与栈顶高度,动态调整左右边界,找到每个子序列的最大面积。
摘要由CSDN通过智能技术生成

题解: - 力扣(LeetCode)

class Solution {
    public int largestRectangleArea(int[] heights) {
        Stack<Integer> stack = new Stack<>();
        int maxArea = Integer.MIN_VALUE;
        for(int i = 0;i < heights.length;i++){
            int curHeight = heights[i];
            while(!stack.empty() && curHeight < heights[stack.peek()]){
                int index = stack.pop();
                int left = (stack.empty()) ? 0 : stack.peek()+1;
                int tempArea = heights[index] * (i - left);
                maxArea = Math.max(maxArea,tempArea);
            }
            stack.push(i);     
        }
        while(!stack.empty()){
                int index = stack.pop();
                int left = (stack.empty()) ? 0 : stack.peek()+1;
                int tempArea = heights[index] * (heights.length - left);
                maxArea = Math.max(maxArea,tempArea);
            }
        return maxArea;
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值