Data Structures & AlgorithmsModerateProduct company OA · Amazon/Microsoft-style OA

What does this program print?

What does this program print?
best = None
s = 0
for x in [4, -2, -2, 3, -1]:
    s += x
    best = s if best is None else max(best, s)
print(best, s)
  1. A. 3 2
  2. B. 4 -1
  3. C. 4 2
  4. D. 4 0

Correct answer: C. 4 2

The running sum takes the values 4, 2, 0, 3, 2. The variable best records the maximum over prefix sums, not over subarrays, so it stops at the largest prefix value 4 while the final sum is 2.

More Coding Interview Problems questions

Exams that ask this topic