当前位置:   article > 正文

[leetcode 中等 最大系列]85. 最大矩形 84. 柱状图中最大的矩形类似_柱状图中最大的矩形 类似

柱状图中最大的矩形 类似

题目描述

给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:6
解释:最大矩形如上图所示。
示例 2:

输入:matrix = []
输出:0
示例 3:

输入:matrix = [["0"]]
输出:0
示例 4:

输入:matrix = [["1"]]
输出:1
示例 5:

输入:matrix = [["0","0"]]
输出:0
 

提示:

rows == matrix.length
cols == matrix[0].length
0 <= row, cols <= 200
matrix[i][j] 为 '0' 或 '1'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

列举所有可能 先算底 再算高

class Solution {
    public int maximalRectangle(char[][] matrix) {
        int rows = matrix.length;
        if(rows == 0) return 0;
        int columns = matrix[0].length;
        int[][] left = new int[rows][columns];

        //寻找每一行横着看的 左边有几个连续的
        for(int i=0;i<rows;i++){
            for(int j=0;j<columns;j++){
                if(matrix[i][j] == '1'){
                    left[i][j] = (j == 0 ? 0:left[i][j-1]) + 1;
                }
            }
        }

        int res = 0;
        for(int i = 0;i < rows; i++){
            for(int j = 0; j < columns; j++){
                if(matrix[i][j] == '1'){
                    //高度为1的
                    int width = left[i][j];
                    int area = width;
                    //高度为2,3,4,5......
                    for(int h = i - 1;h >= 0; h--){
                        width = Math.min(width, left[h][j]);
                        area = Math.max(area, width * (i - h + 1));
                    }
                    res = Math.max(res, area);
                }
            }
        }

       return res;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

单调栈


  • 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/380526
推荐阅读
相关标签
  

闽ICP备14008679号