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 rectangle from (0,0) to (0,1) has sum = 2 + 2 = 4 > k, so we take single cell 2 or rectangle [2,-1] with sum 1, but [2,2] without -1 isn't valid. Best is single cell with value 2.
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 Rectangle No Larger Than KInput Matrix1010-23Best Rectangle: [1,0,1]Sum = 2k = 22 ≤ 2 ✓Output: 2
Understanding the Visualization
1
Matrix Input
2D matrix with positive and negative values
2
Find Rectangles
Search all possible rectangular regions
3
Maximum Valid Sum
Return largest sum that doesn't exceed k
Key Takeaway
🎯 Key Insight: Convert 2D rectangle problem to multiple 1D maximum subarray problems using row compression
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