Max Sum of Rectangle No Larger Than K
1 approach, code in every language
Problem description
You are given an m by n integer matrix and an integer k. Consider every axis-aligned rectangle within the matrix and compute the sum of the values it covers.
Return the largest such rectangle sum that does not exceed k. It is guaranteed that at least one rectangle has a sum no larger than k.
A rectangle is defined by choosing a contiguous range of rows and a contiguous range of columns.
Example 1
Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
The rectangle formed by columns 1 and 2 across both rows has sum 0 + 1 + (-2) + 3 = 2, which is the largest sum that stays at or below k = 2.
Example 2
Input: matrix = [[2,2,-1]], k = 3
Output: 3
The two-column rectangle [2, 2] sums to 4, which exceeds k, so it is rejected. The full row [2, 2, -1] sums to 3, which equals k, so 3 is the largest sum not exceeding k.
Constraints
m == matrix.lengthn == matrix[i].length1 <= m, n <= 100-100 <= matrix[i][j] <= 100-10^5 <= k <= 10^5
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free