LeetCode 题解工作台
重新排列后的最大子矩阵
给你一个二进制矩阵 matrix ,它的大小为 m x n ,你可以将 matrix 中的 列 按任意顺序重新排列。 请你返回最优方案下将 matrix 重新排列后,全是 1 的最大子矩阵面积。 示例 1: 输入: matrix = [[0,0,1],[1,1,1],[1,0,1]] 输出: 4 解…
4
题型
7
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
由于题目中矩阵是按列进行重排,因此,我们可以先对矩阵的每一列进行预处理。 对于每个值为 的元素,我们更新其值为该元素向上的最大连续的 的个数,即 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个二进制矩阵 matrix ,它的大小为 m x n ,你可以将 matrix 中的 列 按任意顺序重新排列。
请你返回最优方案下将 matrix 重新排列后,全是 1 的最大子矩阵面积。
示例 1:

输入:matrix = [[0,0,1],[1,1,1],[1,0,1]] 输出:4 解释:你可以按照上图方式重新排列矩阵的每一列。 最大的全 1 子矩阵是上图中加粗的部分,面积为 4 。
示例 2:

输入:matrix = [[1,0,1,0,1]] 输出:3 解释:你可以按照上图方式重新排列矩阵的每一列。 最大的全 1 子矩阵是上图中加粗的部分,面积为 3 。
示例 3:
输入:matrix = [[1,1,0],[1,0,1]] 输出:2 解释:由于你只能整列整列重新排布,所以没有比面积为 2 更大的全 1 子矩形。
示例 4:
输入:matrix = [[0,0],[0,0]] 输出:0 解释:由于矩阵中没有 1 ,没有任何全 1 的子矩阵,所以面积为 0 。
提示:
m == matrix.lengthn == matrix[i].length1 <= m * n <= 105matrix[i][j]要么是0,要么是1。
解题思路
方法一:预处理 + 排序
由于题目中矩阵是按列进行重排,因此,我们可以先对矩阵的每一列进行预处理。
对于每个值为 的元素,我们更新其值为该元素向上的最大连续的 的个数,即 。
接下来,我们可以对更新后的矩阵的每一行进行排序。然后遍历每一行,计算以该行作为底边的最大全 子矩阵的面积。具体计算逻辑如下:
对于矩阵的某一行,我们记第 大元素的值为 ,其中 ,那么该行至少有 个元素不小于 ,组成的全 子矩阵面积为 。从大到小遍历矩阵该行的每个元素,取 的最大值,更新答案。
时间复杂度 ,空间复杂度 。其中 和 分别是矩阵的行数和列数。
class Solution:
def largestSubmatrix(self, matrix: List[List[int]]) -> int:
for i in range(1, len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]:
matrix[i][j] = matrix[i - 1][j] + 1
ans = 0
for row in matrix:
row.sort(reverse=True)
for j, v in enumerate(row, 1):
ans = max(ans, j * v)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(m \cdot n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates a clear understanding of greedy algorithms and how to apply them to matrix problems.
- question_mark
The candidate is able to articulate the importance of sorting and invariant validation in optimization problems.
- question_mark
The candidate shows awareness of how to manage large inputs efficiently within the problem's constraints.
常见陷阱
外企场景- error
Failing to account for the fact that columns must be rearranged as a whole, not individually.
- error
Overcomplicating the solution by attempting brute force or nested loops instead of leveraging sorting and greedy methods.
- error
Neglecting to validate the arrangement of columns after sorting and failing to track the consecutive 1s correctly.
进阶变体
外企场景- arrow_right_alt
Consider cases where multiple rows are completely filled with 1s, testing the scalability of the solution.
- arrow_right_alt
Extend the problem to non-binary matrices where other values are allowed.
- arrow_right_alt
Explore optimizations that allow solving even larger matrices while maintaining the time complexity.