Predict the output
What does this print?
amounts = [2, 1, 1, 2]
prev2 = prev1 = 0
for a in amounts:
prev2, prev1 = prev1, max(prev1, prev2 + a)
print(prev1, sum(amounts[::2]), sum(amounts[1::2]))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 4 3 3
Right: opening the first and last lockers beats both every-other patterns.
The DP considers every allowed pattern implicitly, including gaps of two, which fixed patterns miss.
Why not the others?
- B 3 3 3. Lockers 0 and 3 are not neighbours, giving 4.
- C 6 3 3. Opening all four breaks the neighbour rule.