How coin change works
dp[v] holds the fewest coins needed to make the amount v. dp[0] is 0 and everything else starts at an impossible value. For each amount from 1 upwards, try every coin that fits: using it costs one coin plus the best answer for v − coin, which is already in the table. Keep the smallest.
The example uses coins [1, 3, 4] and the amount 9, and the table finishes with dp[9] = 3.
What to watch for when it runs
- The dp array is drawn as a row of cells, filled from left to right.
- Every update reads a cell further to the left — an answer that is already final.
- dp[6] settles on 2 (3 + 3): the case a greedy choice gets wrong.
Time and space complexity
- Time
- O(amount × coins)
- Space
- O(amount)
Each amount tries each coin once. If no combination works the cell keeps its impossible value, and the answer is −1.