Max Sum of Rectangle No Larger Than K - Problem

Imagine you're a treasure hunter exploring a 2D grid filled with both precious gems and cursed artifacts. Each cell contains a value that could be positive (gems) or negative (curses). Your goal is to find the most valuable rectangular region you can claim, but there's a catch!

You have a maximum budget of k that represents the most "curse penalty" you can afford to pay. You need to find the rectangle with the maximum sum such that this sum doesn't exceed your budget k.

Input: An m × n integer matrix and an integer k representing your budget.

Output: The maximum sum of any rectangle in the matrix that is ≤ k.

Note: It's guaranteed that at least one valid rectangle exists (worst case, a single non-positive cell).

Input & Output

example_1.py — Basic Case
$ Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
💡 Note: The rectangle with coordinates (0,2) to (1,2) has sum = 1 + 3 = 4, but 4 > 2. The rectangle (0,0) to (0,2) has sum = 1 + 0 + 1 = 2, which equals k.
example_2.py — Single Element
$ Input: matrix = [[2,2,-1]], k = 3
Output: 3
💡 Note: The rectangle (0,0) to (0,1) has sum = 2 + 2 = 4 > 3. The rectangle (0,0) to (0,0) has sum = 2 ≤ 3. The rectangle (0,1) to (0,1) has sum = 2 ≤ 3. The best we can do is sum = 3 from rectangle containing just the first two elements: 2+2=4 is too big, but 2+2-1=3 works if we take (0,0) to (0,2) then subtract... Actually, let's try subarray [2,2] which gives us exactly 3 when we consider [2,1] where 1 comes from 2-1.
example_3.py — All Negative
$ Input: matrix = [[-1,-2],[-3,-4]], k = -1
Output: -1
💡 Note: All elements are negative. The best single element is -1, which equals k exactly. Any larger rectangle would have a more negative (smaller) sum.

Time & Space Complexity

Time Complexity
⏱️
O(m²n²)

O(mn) to build prefix sums + O(m²n²) to check all rectangles with O(1) sum calculation

n
2n
Quadratic Growth
Space Complexity
O(mn)

Additional space for the 2D prefix sum array

n
2n
Linearithmic Space

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 100
  • -100 ≤ matrix[i][j] ≤ 100
  • -105 ≤ k ≤ 105
  • At least one rectangle with sum ≤ k is guaranteed to exist
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen