Max Sum of Rectangle No Larger Than K Problem
Description
LeetCode Problem 363.
Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k.
It is guaranteed that there will be a rectangle with a sum no larger than k.
Example 1:

Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
Explanation: 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).
Example 2:
Input: matrix = [[2,2,-1]], k = 3
Output: 3
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 100-100 <= matrix[i][j] <= 100-10^5 <= k <= 10^5
Follow up: What if the number of rows is much larger than the number of columns?
Solution
Approach: Fix Two Rows + Sorted Prefix Sums
Fix the top row and the bottom row of the rectangle. Every column then collapses into one number, the sum of that column between the two rows. Call this array colSums. A rectangle between those rows is a contiguous range of columns, so the problem becomes one-dimensional: find the largest sum of a subarray of colSums that is no larger than k.
Kadane's algorithm does not help here because of the upper bound, so we use prefix sums. Let s be the prefix sum up to the current column. A subarray ending here has sum s - p for some earlier prefix sum p (including the empty prefix 0). We want s - p <= k and as large as possible, which means p >= s - k and as small as possible. If the earlier prefix sums are kept sorted, that p is a single binary search away (lower_bound / ceiling(s - k)). After the lookup, insert s into the sorted collection.
We enumerate every top row, and grow the bottom row downward one row at a time. That way colSums is updated in O(n) per row pair instead of being recomputed.
Java uses a TreeSet and C++ a std::set. Python, JavaScript and Go keep a sorted array and insert with a binary search. There are at most 101 prefix sums per pass, so shifting the array is cheap. If the best sum ever equals k, nothing can beat it and we stop early.
Follow-up: when there are many more rows than columns, enumerate pairs of columns instead and run the same 1-D search down the rows. That makes the squared factor the small dimension.
Complexity: O(m2 n log n) time: O(m2) row pairs, each with n lookups and inserts. O(n) extra space.
from bisect import bisect_left, insort
class Solution:
def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
m, n = len(matrix), len(matrix[0])
best = float("-inf")
for top in range(m):
col_sums = [0] * n # col_sums[c]: sum of column c from row top to row bottom
for bottom in range(top, m):
for c in range(n):
col_sums[c] += matrix[bottom][c]
# best subarray of col_sums with sum <= k: for each prefix sum s, the smallest
# earlier prefix p with p >= s - k gives the largest s - p that is still <= k
prefixes = [0] # earlier prefix sums, kept sorted
s = 0
for x in col_sums:
s += x
i = bisect_left(prefixes, s - k)
if i < len(prefixes):
best = max(best, s - prefixes[i])
insort(prefixes, s)
if best == k:
return k # cannot do better
return best