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:
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:
is the fewest coins that make cents. The min tries every coin no bigger than . An amount that no coin leads to gets , 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): from the formula, 1 plus the smallest best[t - v] over every coin v that fits, or math.inf if none fits.