Any optimal subrectangle has some top row t and bottom row b . For fixed t , as we increase b , col_sum accumulates. The best subrectangle for that (t,b) corresponds to the best subarray in col_sum . By trying all (t,b) , we cover the optimal solution.
def max_subrectangle_sum(matrix): if not matrix or not matrix[0]: return 0 rows, cols = len(matrix), len(matrix[0]) max_sum = float('-inf') koalas to the max