Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: What is the largest sum of a subarray of length at least 2 in [4, -1, 5, -6, 3, 2]? Run the code.

Problem: What is the largest sum of a subarray of length at least 2 in [4, -1, 5, -6, 3, 2]? Run the code.
a = [4, -1, 5, -6, 3, 2]
best = max(sum(a[i:j]) for i in range(len(a)) for j in range(i + 2, len(a) + 1))
print(best)
What is printed?
  1. A. 9
  2. B. 7
  3. C. 8
  4. D. 5

Correct answer: C. 8

[4, −1, 5] sums to 8, which is also the unrestricted maximum here. Skipping the −1 (a subsequence, not a subarray) gives 9, the whole array gives 7, and exactly-length-2 windows give at most 3 + 2 = 5.

More Coding Interview Problems questions

Exams that ask this topic