Skip to content

Dynamic programming · stretch

No two neighbours

Write best_total(values) returning the largest sum you can take from the list without ever taking two neighbours. [2, 7, 9, 3, 1] gives 12 (2 + 9 + 1).

At each item: take it plus the best up to two before, or skip it and keep the best up to one before.

Run adds print(best_total([2, 7, 9, 3, 1])) after your code, to try it.

Stuck on the idea rather than the code? The Tables and choices lesson walks through it.