84. 柱状图中最大的矩形

该博客介绍了如何解决LeetCode上的最大矩形面积问题,提供了两种算法实现:一种是使用双指针暴力穷举法,另一种是利用单调栈优化解法。博主详细解释了每种方法的思路,并给出了对应的Java代码实现。文章重点讨论了单调栈解法,通过维护一个单调递减的栈来跟踪高度,从而有效地计算出最大矩形的面积。
摘要由CSDN通过智能技术生成

题目:https://leetcode-cn.com/problems/largest-rectangle-in-histogram/
目的:找到面积最大的矩形
面积 = 高度 * 宽度
高度确定,宽度不确定
1 暴力穷举法
思路:双指针。
1.1 左指针向左移动,直到第一个比自己矮的矩形
1.2 右指针向右移动,直到第一个比自己矮的矩形

class Solution {
    public int largestRectangleArea(int[] heights) {
      
        int len = heights.length;
        int[] arr = new int[len+2];
        for (int i = 0; i< heights.length; i++) {
            arr[i+1] = heights[i];
        }
        int ans = 0;
        for (int i = 1; i < arr.length-1; i++) {
            int currentHeight = arr[i];
            int left = i; 
            int right = i;
            while (left > 0 && arr[left] >= arr[i] ) {
                left--;
            }
            while (right < arr.length-1 && arr[right] >= arr[i]) {
                right++;
            }
            ans = Math.max(ans, currentHeight * (right - left-1));
        }
        return ans;
    }
}

2 单调栈
定义一个栈,指针向右移动,比自己高就入栈,直到遇到比自己低的矩形,不入栈,而是出栈,一直出到比自己矮的矩形

class Solution {
    public int largestRectangleArea(int[] heights) {
        // 单调栈 https://leetcode-cn.com/problems/largest-rectangle-in-histogram/solution/java-shuang-jie-fa-dai-ma-jian-ji-yi-dong-dan-diao/
        int len = heights.length;
        int[] arr = new int[len+2];
        for (int i = 0; i< len; i++) {
            arr[i+1] = heights[i];
        } 
        // heights [2, 1, 5, 6, 2, 3]
        // arr  [0, 2, 1, 5, 6, 2, 3, 0]

        int res = 0;
        int index = 1;
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(0);
        while (index < arr.length) {
            while (index < arr.length && arr[index] >= arr[stack.peek()]) {
                stack.push(index);
                index++;
            }
            while (index < arr.length && arr[index] < arr[stack.peek()]) {
                int curHeight = arr[stack.pop()];
                res = Math.max(res, curHeight * (index - stack.peek() - 1));
            }
        }
        return res;
    }
}

推荐题解: https://leetcode-cn.com/problems/largest-rectangle-in-histogram/solution/java-shuang-jie-fa-dai-ma-jian-ji-yi-dong-dan-diao/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值