Predict the output
What does this print?
vals = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
run = best = vals[0]
for v in vals[1:]:
run = max(v, run + v)
best = max(best, run)
print(best)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 6
Right: the run 4, -1, 2, 1 adds up to 6.
A run is worth keeping only while its total is positive, which is the choice the max() makes each step.
Why not the others?
- B 7. Extending to include the 4 at the end adds -5 first.
- C 4. Extending 4 through -1, 2 and 1 does better.