Greedy fails here: with coins [1, 3, 4] and amount 6, taking the biggest coin first gives 4+1+1 (three coins) but 3+3 is better. Dynamic programming fixes this by computing the best answer for every smaller amount first.
A shop till never runs out of coins of each value listed in coins. Write coin_change(coins, amount) that returns the fewest coins whose values add up to exactly amount, or -1 if no mix of coins makes that amount.
Examples
Input: coins = [1, 4, 6], amount = 9
Output: 3
Explanation: 4 + 4 + 1 (starting with the 6 needs 6 + 1 + 1 + 1)
Input: coins = [3, 6], amount = 10
Output: -1
Explanation: every mix of these coins totals a multiple of 3
Input: coins = [2, 7], amount = 0
Output: 0
Constraints
- Target: O(amount * len(coins)) time
Goals
- Define a DP state as 'fewest coins to make amount a' and fill it bottom-up
- Use an 'infinity' sentinel for unreachable states
- See why the greedy 'take the biggest coin' approach fails