Predict the output
What does this print?
vals = [-2, 3, -4]
hi = lo = best = vals[0]
for v in vals[1:]:
hi, lo = max(v, hi * v, lo * v), min(v, hi * v, lo * v)
best = max(best, hi)
print(best)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 24
Right: the whole run, -2 × 3 × -4, is positive.
The smallest product (-6) becomes the largest after multiplying by -4, which is why both are carried.
Why not the others?
- B 3. Tracking only the largest would stop at 3.
- C 12. 3 × -4 is negative; the full run gives 24.