Max Sum of Rectangle No Larger Than K

HardMatrixprefix sum

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an m x n integer matrix matrix and an integer k, consider every non-empty axis-aligned sub-rectangle of the matrix. Return the largest rectangle sum that is less than or equal to k. It is guaranteed that at least one rectangle has a sum no larger than k. A good target is O(min(m,n)^2 * max(m,n) * log(max(m,n))): fix a pair of rows (or columns), collapse to a 1-D array, and find the best subarray sum not exceeding k using sorted prefix sums.

Examples

Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
The rectangle [[0,1],[-2,3]] sums to 2, which is the largest sum not above 2.
Input: matrix = [[2,2,-1]], k = 3
Output: 3
The first two cells sum to 4 (too big), but all three cells sum to exactly 3.

Constraints

  • 1 <= m, n <= 100
  • -100 <= matrix[i][j] <= 100
  • -10^5 <= k <= 10^5
  • At least one rectangle has sum <= k

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More prefix sum problems