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
Time & Space Complexity
O(mn) to build prefix sums + O(m²n²) to check all rectangles with O(1) sum calculation
Additional space for the 2D prefix sum array
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