Skip to content

363. Max Sum Of Rectangle No Larger Than K

Array Binary Search Matrix Prefix Sum Ordered Set

Problem - Max Sum Of Rectangle No Larger Than K

Hard

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.

 

Example 1:

Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).

Example 2:

Input: matrix = [[2,2,-1]], k = 3
Output: 3

 

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -100 <= matrix[i][j] <= 100
  • -105 <= k <= 105

 

Follow up: What if the number of rows is much larger than the number of columns?

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
        m, n = len(matrix), len(matrix[0])
        result = -inf

        for i in range(m):
            nums = [0] * n
            for j in range(i, m):
                for h in range(n):
                    nums[h] += matrix[j][h]

                temp_sum = 0
                sorted_set = SortedSet([0])
                for val in nums:
                    temp_sum += val
                    l = sorted_set.bisect_left(temp_sum - k)
                    if l != len(sorted_set):
                        result = max(result, temp_sum - sorted_set[l])
                    sorted_set.add(temp_sum)

        return result

Submission Stats:

  • Runtime: 2817 ms (11.58%)
  • Memory: 18.7 MB (30.35%)