[LeetCode] 1727. Largest Submatrix With Rearrangements

发布时间 2023-11-30 01:56:43作者: CNoodle

You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order.

Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.

Example 1:
Example 1
Input: matrix = [[0,0,1],[1,1,1],[1,0,1]]
Output: 4
Explanation: You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.

Example 2:
Example 1
Input: matrix = [[1,0,1,0,1]]
Output: 3
Explanation: You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.

Example 3:
Input: matrix = [[1,1,0],[1,0,1]]
Output: 2
Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.

Constraints:
m == matrix.length
n == matrix[i].length
1 <= m * n <= 105
matrix[i][j] is either 0 or 1.

重新排列后的最大子矩阵。

给你一个二进制矩阵 matrix ,它的大小为 m x n ,你可以将 matrix 中的 列 按任意顺序重新排列。
请你返回最优方案下将 matrix 重新排列后,全是 1 的子矩阵面积。

思路

类似85题,我们先从上到下记录矩阵里每一列出现的连续的 1 的个数,比如第一个例子,matrix = [[0,0,1],[1,1,1],[1,0,1]],从上到下记录之后,矩阵变成
matrix = [
[0,0,1],
[1,1,2],
[2,0,3]
]

然后我们对这个矩阵逐行扫描,看一下如果以当前行为结尾,能组成的最大子矩阵的面积是多少。这样一来这道题就跟85题很像了。

复杂度

时间O(mn)
空间O(1)

代码

Java实现

class Solution {
    public int largestSubmatrix(int[][] matrix) {
        // corner case
        if (matrix == null || matrix.length == 0) {
            return 0;
        }

        // normal case
        int m = matrix.length;
        int n = matrix[0].length;
        for (int i = 1; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == 1) {
                    matrix[i][j] += matrix[i - 1][j];
                }
            }
        }

        int res = 0;
        for (int i = 0; i < m; i++) {
            Arrays.sort(matrix[i]);
            for (int j = n - 1; j >= 0; j--) {
                int area = matrix[i][j] * (n - j);
                res = Math.max(res, area);
            }
        }
        return res;
    }
}

相关题目

84. Largest Rectangle in Histogram
85. Maximal Rectangle
221. Maximal Square
1277. Count Square Submatrices with All Ones
1727. Largest Submatrix With Rearrangements