Largest Submatrix With Rearrangements LeetCode solution in Python
1# Runtime: 3821 ms (Top 7.64%) | Memory: 37.3 MB (Top 95.14%)2from collections import Counter345class Solution:6def largestSubmatrix(self, matrix: List[List[int]]) -> int:7M = len(matrix)8N = len(matrix[0])910colcons = [] # preprocess columns11for c in range(N):12cons = []13s = 014for r in range(M):15if not matrix[r][c]:16s = 017else:18s += 119cons.append(s)20colcons.append(cons)21# colcons[c][r] is how much 1's we'll get if we start from column c at row r and go up2223best = 024for r in range(M):25# try r as the lowest row26C = Counter(colcons[c][r] for c in range(N))27vs = sorted(C.keys(), reverse=True)28cs = accumulate(C[v] for v in vs)29for v, c in zip(vs, cs):30best = max(best, v * c)31return best