Max Sum of Rectangle No Larger Than K LeetCode solution in Python
1class Solution:2def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:3import numpy as np45matrix = np.array(matrix, dtype=np.int32)67M, N = matrix.shape89ret = float("-inf")1011CUM = np.zeros((M, N), dtype=np.int32)12for shift_r in range(M):13CUM[: M - shift_r] += matrix[shift_r:]1415_CUM = np.zeros((M - shift_r, N), dtype=np.int32)16for shift_c in range(N):17_CUM[:, : N - shift_c] += CUM[: M - shift_r, shift_c:]18tmp = _CUM[(_CUM <= k) & (_CUM > ret)]19if tmp.size:20ret = tmp.max()21if ret == k:22return ret2324return ret