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 withinmatrixwhere every element of the submatrix is1after reordering the columns optimally.
Input: matrix = [[0,0,1],[1,1,1],[1,0,1]]Output: 4Explanation: You can rearrange the columns as shown above.The largest submatrix of 1s, in bold, has an area of 4.
Input: matrix = [[1,0,1,0,1]]Output: 3Explanation: You can rearrange the columns as shown above.The largest submatrix of 1s, in bold, has an area of 3.
Input: matrix = [[1,1,0],[1,0,1]]Output: 2Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
class Solution: # Time: O(m * n log n) # Space: O(n) def largest_submatrix(self, matrix: list[list[int]]) -> int: n = len(matrix[0]) heights = [0] * n best = 0 for row in matrix: for j, val in enumerate(row): heights[j] = heights[j] + 1 if val else 0 sorted_heights = sorted(heights, reverse=True) for i, h in enumerate(sorted_heights): best = max(best, h * (i + 1)) return best