Given coin denominations coins and a target amount, return the fewest coins that sum exactly to amount. You have unlimited coins of each denomination. If the amount cannot be made, return -1. An amount of zero needs zero coins.
Dynamic programming — being able to say, in one sentence, what a single cell of your table MEANS. Everything else follows from that sentence. Rolling variables: when a state only looks back one or two steps, the table collapses to a couple of numbers.
How to think about it
1. Try Every Coin Last, Keep the Fewest Optimal
Intuition
Look at the last coin in the fewest-coin way to make an amount. It could be any of the coins, and taking it off leaves a smaller amount, which has to be made the fewest way too. So the fewest coins for an amount is one more than the fewest for the amount minus some coin, and since which coin is not known, every coin that fits is tried and the smallest kept. Grabbing the largest coin first is not that: with coins of 4, 3 and 1 and an amount of 6, it takes a 4 and two 1s, three coins, where a 3 and a 3 are two. Each try needs a smaller amount's answer first, so fill a table from 0 up to the target. For every amount up to the target, try each coin last and keep the fewest.
Algorithm
1. Make a table, fewest, of amount + 1 counts: one for every amount from 0 to the target, each starting at amount + 1, more coins than any answer could use, so not made yet. 2. An amount of 0 takes no coins: fewest[0] = 0. 3. For every total from 1 to amount, try each coin that fits: with that coin last, the count is fewest[total - coin] + 1. 4. Keep the smallest: fewest[total] is the smaller of the count so far and fewest[total - coin] + 1. 5. After the last total, an amount still above amount was never made: return -1. Otherwise return fewest[amount].
Time & Space
Time O(amount × coins): every total tries every coin once. Space O(amount) for the table of amount + 1 counts.
2. Fewest Coins for Every Amount Below Optimal
Intuition
best[a] means "the fewest coins that make exactly a" — say that sentence and the recurrence writes itself: try each coin as the LAST one used and take the cheapest of best[a - coin] + 1. Greedy largest-first is the trap, and [186,419,83,408] is in the tests because it fails there: taking the biggest coin can strand the remainder.
Algorithm
1. best[0] is zero coins; every other amount starts unreachable. 2. For each amount upward, try every coin that fits. 3. Take the cheapest of best[amount - coin] + 1. 4. An amount still unreachable at the end answers -1.