Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the maximum sum of a subarray of size exactly k, and the sum of the best circular subarray (wrapping allowed).

Problem: Return the maximum sum of a subarray of size exactly k, and the sum of the best circular subarray (wrapping allowed).
def best_k(a, k):
    s = best = sum(a[:k])
    for i in range(k, len(a)):
        s += a[i] - a[i - k]; best = max(best, s)
    return best
def best_circ(a):
    cur_max = cur_min = 0; mx, mn = a[0], a[0]
    for x in a:
        cur_max = max(x, cur_max + x); mx = max(mx, cur_max)
        cur_min = min(x, cur_min + x); mn = min(mn, cur_min)
    return mx if mx < 0 else max(mx, sum(a) - mn)
print(best_k([1, 4, 2, 10, 23, 3, 1, 0, 20], 4), best_circ([5, -3, 5]), best_circ([-3, -2, -3]))
What is printed?
  1. A. 39 7 -2
  2. B. 36 10 -2
  3. C. 39 10 -8
  4. D. 39 10 -2

Correct answer: D. 39 10 -2

Fixed window: slide and update the sum in O(1): 4 + 2 + 10 + 23 = 39. Circular: the best wrap-around subarray is total − (minimum subarray): 7 − (−3) = 10. If every value is negative, total − min would be the empty subarray (0), so return the plain maximum −2 instead. O(n).

More Coding Interview Problems questions

Exams that ask this topic