Skip to content

363. Max Sum of Rectangle No Larger Than K 👍

  • Time: $O(\min(m, n)^2 \cdot \max(m, n) \cdot \log\max(m, n))$
  • Space: $O(\max(m, n))$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
 public:
  int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
    const int m = matrix.size();
    const int n = matrix[0].size();
    int ans = INT_MIN;

    for (int baseCol = 0; baseCol < n; ++baseCol) {
      // sums[i] := sum(matrix[i][baseCol..j])
      vector<int> sums(m, 0);
      for (int j = baseCol; j < n; ++j) {
        for (int i = 0; i < m; ++i)
          sums[i] += matrix[i][j];
        // Find the maximum sum <= k of all the subarrays.
        set<int> accumulate{0};
        int prefix = 0;
        for (const int sum : sums) {
          prefix += sum;
          if (const auto it = accumulate.lower_bound(prefix - k);
              it != accumulate.cend())
            ans = max(ans, prefix - *it);
          accumulate.insert(prefix);
        }
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
  public int maxSumSubmatrix(int[][] matrix, int k) {
    final int m = matrix.length;
    final int n = matrix[0].length;
    int ans = Integer.MIN_VALUE;

    for (int baseCol = 0; baseCol < n; ++baseCol) {
      // sums[i] := sum(matrix[i][baseCol..j])
      int[] sums = new int[m];
      for (int j = baseCol; j < n; ++j) {
        for (int i = 0; i < m; ++i)
          sums[i] += matrix[i][j];
        // Find the maximum sum <= k of all the subarrays.
        TreeSet<Integer> accumulate = new TreeSet<>(Arrays.asList(0));
        int prefix = 0;
        for (final int sum : sums) {
          prefix += sum;
          final Integer lo = accumulate.ceiling(prefix - k);
          if (lo != null)
            ans = Math.max(ans, prefix - lo);
          accumulate.add(prefix);
        }
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from sortedcontainers import SortedList


class Solution:
  def maxSumSubmatrix(self, matrix: list[list[int]], k: int) -> int:
    m = len(matrix)
    n = len(matrix[0])
    ans = -math.inf

    for baseCol in range(n):
      # sums[i] := sum(matrix[i][baseCol..j])
      sums = [0] * m
      for j in range(baseCol, n):
        for i in range(m):
          sums[i] += matrix[i][j]
        # Find the maximum sum <= k of all the subarrays.
        accumulate = SortedList([0])
        prefix = 0
        for summ in sums:
          prefix += summ
          it = accumulate.bisect_left(prefix - k)
          if it != len(accumulate):
            ans = max(ans, prefix - accumulate[it])
          accumulate.add(prefix)

    return ans