Largest Submatrix With Rearrangements — LeetCode 1727 Python Solution
- Problem
- #1727
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- Input
- matrix = [[0,0,1],[1,1,1],[1,0,1]]
- Output
- 4
- Explanation
- You can rearrange the columns as shown above.
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n \times \log n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1727. Largest Submatrix With Rearrangements is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1727. Largest Submatrix With Rearrangements?
- LeetCode 1727. Largest Submatrix With Rearrangements is rated Medium on LeetCode.
- What topics does LeetCode 1727. Largest Submatrix With Rearrangements cover?
- LeetCode 1727. Largest Submatrix With Rearrangements is tagged Greedy, Array, Matrix and Sorting on LeetCode.