Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

Problem: What is the maximum sum of a contiguous subarray of exactly length 3 in [5, -2, 7, 1, 0, 4]?

Problem: What is the maximum sum of a contiguous subarray of exactly length 3 in [5, -2, 7, 1, 0, 4]?
a = [5, -2, 7, 1, 0, 4]
print(max(sum(a[i:i + 3]) for i in range(len(a) - 2)))
What is printed?
  1. A. 15
  2. B. 10
  3. C. 8
  4. D. 11

Correct answer: B. 10

The windows of size 3 sum to 10, 6, 8 and 5, so the best is 5, −2, 7 = 10. Kadane's maximum subarray of any length gives 15, a window of size 2 gives 7 + 1 = 8, and a window of size 4 gives 5 − 2 + 7 + 1 = 11.

More Coding Interview Problems questions

Exams that ask this topic