Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Find the maximum sum of a sub-rectangle whose sum does not exceed k (fix two columns, then 'max subarray sum ≤ k' with a sorted prefix list).

Problem: Find the maximum sum of a sub-rectangle whose sum does not exceed k (fix two columns, then 'max subarray sum ≤ k' with a sorted prefix list).
from bisect import bisect_left, insort
def best(m, k):
    R, C = len(m), len(m[0]); ans = float('-inf')
    for c1 in range(C):
        rows = [0] * R
        for c2 in range(c1, C):
            for r in range(R): rows[r] += m[r][c2]
            pre, s = [0], 0
            for x in rows:
                s += x; i = bisect_left(pre, s - k)
                if i < len(pre): ans = max(ans, s - pre[i])
                insort(pre, s)
    return ans
print(best([[1, 0, 1], [0, -2, 3], [2, 1, -1]], 2), best([[2, 2, -1]], 3))
What is printed?
  1. A. 3 3
  2. B. 2 3
  3. C. 2 4
  4. D. 1 2

Correct answer: B. 2 3

For each pair of columns, row sums form a 1-D array; the best subarray sum ≤ k is s − (smallest prefix ≥ s − k). First matrix: a sum of exactly 2 is achievable (e.g. [1, 0, 1] in row 0), so 2. Second: [2, 2] = 4 exceeds 3, while [2, −1] = 1, [2] = 2 and [2, 2, −1] = 3 → 3.

More Coding Interview Problems questions

Exams that ask this topic