6/28
Part 2 of 7 · Spot the dynamic programLearn and do

Spot the dynamic program

The best way to make 6 cents is one coin plus a best way to make the rest

Say the coins are 1, 3 and 4 cents, and you want 6 cents. Some coin comes last. Try each one:

Fewest coins for 6 cents, from coins of 1, 3 and 4Interactive
Coins: 1, 3, 4. Tap a cell to see where its number comes from.
best[6]: via 1: best[5] + 1 = 3, via 3: best[3] + 1 = 2, via 4: best[2] + 1 = 3. The smallest, 2, wins.

Tap 6: you don't know which coin comes last, so try them all and keep the smallest. Then tap the smaller amounts. As a formula:

F(t)=1+min⁡c ≤ tF(t−c),F(0)=0F(t) = 1 + \min_{c \,\le\, t} F(t - c), \qquad F(0) = 0

F(t)F(t) is the fewest coins that make tt cents. The min tries every coin cc no bigger than tt. An amount that no coin leads to gets F(t)=∞F(t) = \infty, which means unreachable.

This works because the rest has to be a best answer too. Say the best way to make 6 cents ends with a 3-cent coin. The other coins make 3 cents. If a better way to make 3 cents existed, you could swap it in and beat the best answer for 6, which can't happen. This is called optimal substructure: the best answer is built from best answers to smaller problems.

In the editor, best already holds the fewest coins for 0 to 5 cents, from coins of 1, 3 and 4. Write cell(t, values, best): F(t)F(t) from the formula, 1 plus the smallest best[t - v] over every coin v that fits, or math.inf if none fits.