Max Sum of Rectangle No Larger Than K - Problem

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.

A rectangle is defined by its top-left corner and bottom-right corner.

Input & Output

Example 1 — Basic Case
$ Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
💡 Note: The rectangle with corners (0,0) to (0,2) has sum = 1 + 0 + 1 = 2, which equals k
Example 2 — Single Cell
$ Input: matrix = [[2,2,-1]], k = 3
Output: 3
💡 Note: The entire rectangle [2,2,-1] has sum = 2 + 2 + (-1) = 3, which equals k
Example 3 — Negative Values
$ Input: matrix = [[-1,2],[-1,3]], k = 0
Output: 0
💡 Note: Rectangle from (0,1) to (1,0) would be invalid. Single cells: -1,-1,2,3. Rectangles: [-1,2]=1, [-1,3]=2, [2,3]=5, [-1,-1]=-2, full=3. Only -1 ≤ 0, and -2 ≤ 0. Best is -1.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 100
  • -100 ≤ matrix[i][j] ≤ 100
  • -105 ≤ k ≤ 105

Visualization

Tap to expand
Max Sum of Rectangle No Larger Than K INPUT Matrix (2x3): 1 0 1 0 -2 3 r0 r1 c0 c1 c2 k = 2 Find rectangle with max sum <= k Possible rectangles: 1x1 1x2 2x1 2x2 ALGORITHM STEPS 1 Fix Left-Right Cols Iterate all column pairs 2 Compress to 1D Sum rows between cols s0 s1 ... 3 Kadane + TreeSet Find max subarray <= k For each prefix sum S: Find smallest X where X >= S - k (binary search) 4 Track Maximum Update best sum <= k ans = max(ans, S - X) FINAL RESULT Optimal Rectangle Found: 1 0 1 0 -2 3 Rectangle: col1, row0-1 Sum: 0 + (-2) = -2 OR single cell [0][2]: 1 Best: cells summing to 2 Output: 2 OK - Max sum <= k Key Insight: Reduce 2D problem to 1D by fixing column boundaries. For each pair of columns (L,R), compress rows into a 1D array. Use prefix sums + TreeSet to find max subarray sum <= k via binary search: for prefix S, find smallest X >= S-k in TreeSet. Time: O(m^2 * n * log(n)). Space: O(n) for compressed array and TreeSet. TutorialsPoint - Max Sum of Rectangle No Larger Than K | Kadane + Binary Search Approach
Asked in
Google 45 Microsoft 35 Amazon 30 Facebook 25
89.0K Views
Medium Frequency
~35 min Avg. Time
1.8K 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