03. Max Sum of Rectangle No Larger Than K
Given an $m \times n$ matrix and an integer $k$, return the max sum of a rectangle in the matrix such that its sum is no larger than $k$.
How It Works & Algorithmic Design
Solves using 1D Sub-Array Projection with Sorted Binary Search TreeSet:
- Row Interval Bounds: Fix top row
r1and bottom rowr2($0 \le r1 \le r2 < m$). - 1D Projection: Accumulate row values into 1D array
sums[c] += matrix[r2][c]. - Binary Search Prefix Sums:
- Maintain running sum
currSumand prefix sums in a sorted array/TreeSetset = [0]. - Find smallest
Pinsetsuch thatcurrSum - P <= k$\to$P >= currSum - k. - If found,
maxSum = Math.max(maxSum, currSum - P). - Insert
currSumintoset.
- Maintain running sum
Why This Approach Works Best
Binary search prefix sets evaluate optimal rectangle bounds in $O(m^2 \cdot n \log n)$ time.
Example Walkthrough
Input Matrix
[[1,0,1],[0,-2,3]], k = 2
Matrix and target bound k.
Max Sub-matrix
Rectangle [[0, 1], [-2, 3]] has sum 2 <= k.
Bounded rectangle sum.
Output
2
Max sum <= k.
Answer: Max Sum Rectangle No Larger Than K implementation
function maxSumSubmatrix(matrix, k) {
const m = matrix.length, n = matrix[0].length;
let maxSum = -Infinity;
for (let l = 0; l < n; l++) {
const rowSums = new Array(m).fill(0);
for (let r = l; r < n; r++) {
for (let i = 0; i < m; i++) rowSums[i] += matrix[i][r];
const set = [0];
let curr = 0;
for (const sum of rowSums) {
curr += sum;
// Binary search for smallest val >= curr - k
const target = curr - k;
let low = 0, high = set.length - 1, match = -1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (set[mid] >= target) { match = set[mid]; high = mid - 1; }
else low = mid + 1;
}
if (match !== -1) maxSum = Math.max(maxSum, curr - match);
// Insert curr in sorted array
let pos = 0;
while (pos < set.length && set[pos] < curr) pos++;
set.splice(pos, 0, curr);
}
}
}
return maxSum;
}Compress matrix rows into 1D arrays and find maximum bounded sums using binary search prefix sets.
Key Takeaways
Converts 2D sub-matrix search into 1D prefix arrays.
Uses binary search (
ceiling) to find sub-array sums $\le k$.Runs in $O(m^2 \cdot n \log n)$ time.