#1727
Largest Submatrix With Rearrangements
MediumArrayGreedySortingMatrixDynamic ProgrammingSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m * n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(m * n log n)Space O(n)
The optimal approach focuses on calculating the height of consecutive 1s for each column and then sorting these heights for each row. This allows us to efficiently compute the maximum area of 1s by rearranging columns.
⚙️
Algorithm
4 steps- 1Step 1: Create an array to store the heights of consecutive 1s for each column.
- 2Step 2: For each row, update the heights based on the current row's values.
- 3Step 3: Sort the heights in non-increasing order and calculate the area for each height considering its position.
- 4Step 4: Keep track of the maximum area found.
solution.py16 lines
1# Full working Python code
2
3def largestSubmatrix(matrix):
4 if not matrix:
5 return 0
6 m, n = len(matrix), len(matrix[0])
7 heights = [0] * n
8 max_area = 0
9 for row in matrix:
10 for j in range(n):
11 heights[j] = heights[j] + 1 if row[j] == 1 else 0
12 sorted_heights = sorted(heights, reverse=True)
13 for i in range(n):
14 max_area = max(max_area, sorted_heights[i] * (i + 1))
15 return max_area
16ℹ
Complexity note: The complexity arises from iterating through each row and sorting the heights, which is efficient compared to the brute-force method.
- 1Understanding how to manipulate matrix dimensions can lead to significant optimizations.
- 2Sorting can help in rearranging columns effectively to maximize areas.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.