Problem 363 · LeetCode 363(opens in a new tab)
Max Sum of Rectangle No Larger Than K
HardBinary search
You get an m × n grid of integers, matrix, and an integer k. A rectangle is any block of cells with sides along the grid lines, from a single cell up to the whole grid.
Return the largest rectangle sum that does not go over k. At least one rectangle is guaranteed to have a sum of k or less.
Example 1
Input: matrix = [[6, 2], [-2, 3]], k = 5 Output: 5 Why: the right column gives 2 + 3 = 5; the 6 alone is too big
2 more examples and the constraints
Example 2
Input: matrix = [[4, -1, 2]], k = 3 Output: 3 Why: 4 + (−1) = 3 is exactly k
Example 3
Input: matrix = [[-3, -1], [-4, -2]], k = 100 Output: -1 Why: every sum is negative, so the best is the single −1
Constraints
- The grid has 1 to 100 rows and 1 to 100 columns
- Every cell holds a value from −100 to 100
- −100,000 ≤ k ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every rectangle with 2D prefix sumsO(m² · n²)
- Row strips and a sorted set of prefixesO(m² · n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 100 × 100 grid | Verdict |
|---|---|---|---|
| Every rectangle with 2D prefix sums | O(m² · n²) | Simple, but 25 million rectangles | |
| Row strips and a sorted set of prefixes | O(m² · n log n) | Best; one sorted lookup per column |
m = the shorter side, n = the longer side, both at most 100.
Edge cases to test
- All negative. The best can be a single cell, here −1, and it is fine for the answer to be negative.
- k is exactly reachable. Return k; a sum equal to k counts.
- k is very negative. A 50 × 50 grid of −100 with k = −100,000 needs a rectangle of 1,000 cells.
- One row or one column. The problem becomes the 1D version directly.
- Far more rows than columns. Pair the columns instead, so the squared factor is the small side.
Common mistakes
- Using Kadane's maximum subarray and capping it at k, which can miss a smaller sum that fits.
- Forgetting the strip that starts at column 0 (no earlier prefix to subtract, or a stored 0).
- Searching for the largest p ≤ s − k instead of the smallest p ≥ s − k.
How to talk through it
- 1Clarify. Can values and k be negative? Is a single cell a rectangle? Is an answer guaranteed?
- 2Brute force first. 2D prefix sums make each of the m²n² rectangles O(1).
- 3Reduce to 1D. Fix the top and bottom rows, and the column sums turn rectangles into subarrays.
- 4Handle the cap. For prefix s, the best start is the smallest earlier prefix ≥ s − k: a sorted set with ceiling or lower_bound.
- 5Test out loud. Run Example 1, an all-negative grid, and a tall grid where the sides should be swapped.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?