HardArrayBinary SearchMatrixOrdered SetPrefix Sum

Max Sum of Rectangle No Larger Than K

LeetCode
1 approach, code in all languages

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.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -100 <= matrix[i][j] <= 100
  • -10^5 <= k <= 10^5
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now