LeetCode085——最大矩形

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/maximal-rectangle/description/

题目描述:

知识点:栈、动态规划

思路:LeetCode084——柱状图中最大的矩形的变形

(1)对于二维数组matrix中的每一行,计算包括该行及该行之前所有行在内的1的高度。这个过程可以用动态规划来解决。

状态定义

f(x, y)--------第x行第y列位置垂直方向上1的连续高度。

状态转移

当x == 0时,f(x, y) = matrix(x, y) - '0'。这是第一行。

当x > 0时,如果matrix(x, y) == '0',则f(x, y) = 0。否则,f(x, y) = f(x - 1, y) + 1。

(2)对于每一行,将其看成是有高度的矩形,就是对于每一行求解LeetCode084——柱状图中最大的矩形的问题。

时间复杂度和空间复杂度均是O(m * n),其中m为matrix矩阵的行数,n为matrix矩阵的列数。

JAVA代码:

public class Solution {

    public int maximalRectangle(char[][] matrix) {
        int m = matrix.length;
        if(m == 0){
            return 0;
        }
        int n = matrix[0].length;
        int[][] heights = new int[m][n];
        for (int i = 0; i < n; i++) {
            heights[0][i] = matrix[0][i] - '0';
        }
        for (int i = 1; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(matrix[i][j] == '0'){
                    heights[i][j] = 0;
                }else{
                    heights[i][j] = heights[i - 1][j] + 1;
                }
            }
        }
        int result = 0;
        for (int i = 0; i < m; i++) {
            result = Math.max(result, maximalRectangle(heights[i]));
        }
        return result;
    }

    //LeetCode084
    private int maximalRectangle(int[] heights){
        int n = heights.length;
        int[] newHeights = new int[n + 1];
        for (int i = 0; i < n; i++) {
            newHeights[i] = heights[i];
        }
        newHeights[n] = 0;
        int result = 0;
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < n + 1; i++) {
            while(!stack.isEmpty() && newHeights[stack.peek()] >= newHeights[i]){
                int index = stack.pop();
                int left = stack.isEmpty() ? -1 : stack.peek();
                result = Math.max(result, (i - left - 1) * newHeights[index]);
            }
            stack.push(i);
        }
        return result;
    }
}

LeetCode解题报告:

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值