Given an <code>m x n</code> matrix <code>matrix</code> and an integer <code>k</code>, return <em>the max sum of a rectangle in the matrix such that its sum is no larger than</em> <code>k</code>.It is <strong>guaranteed</strong> that there will be a rectangle with a sum no larger than <code>k</code>.
Input: matrix = [[1,0,1],[0,-2,3]], k = 2Output: 2Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).
from bisect import bisect_left, insortclass Solution: # Time: O(m^2 * n * log n) # Space: O(n) def max_sum_submatrix(self, matrix: list[list[int]], k: int) -> int: rows, cols = len(matrix), len(matrix[0]) best = -(10**9) for top in range(rows): col_sums = [0] * cols for bottom in range(top, rows): row = matrix[bottom] for c in range(cols): col_sums[c] += row[c] sorted_sums = [0] running = 0 for s in col_sums: running += s i = bisect_left(sorted_sums, running - k) if i < len(sorted_sums): best = max(best, running - sorted_sums[i]) insort(sorted_sums, running) return best