Watch the coin change DP table find the fewest coins for every amount. Worked example with coins 1, 3, 4 for amount 6, or type your own coins and amount.
About this algorithm
Coin change asks for the fewest coins that add up to an amount, when you have an unlimited supply of each coin value. Dynamic programming solves it with a table of the fewest coins for every amount from 0 up to the target, where each amount is one coin plus the best answer for the amount left over, already solved. It is LeetCode 322.
Use this table whenever you do not know that the coin system is canonical, or simply want an answer that is always right. The greedy coin change page takes the biggest coin first, which is faster but only works for systems like US or euro coins. If the question is how many different ways there are to make the amount, that is Coin Change II (LeetCode 518), the same table with sums of counts instead of a minimum. If each coin may be used only once, it becomes a 0/1 knapsack style problem.
Make dp with one slot per amount from 0 to the target. dp[0] = 0, since zero coins make zero, and every other slot starts at infinity, meaning not yet reachable.
For amount a from 1 up, and for each coin c no bigger than a, the candidate is dp[a - c] + 1: the best way to make a - c, plus this coin. Keep the smallest candidate in dp[a], and remember which coin gave it in last[a].
If dp[target] is still infinity, no combination works and the answer is -1. Otherwise dp[target] is the fewest coins.
From the target, take the coin in last[a], subtract it, and repeat until you reach 0. The coins you took are one best answer.
The page opens on coins 1, 3 and 4 and the amount 6. dp[1] = 1 and dp[2] = 2, using only 1s. dp[3] = 1 with a single 3, and dp[4] = 1 with a single 4. For dp[5] the coin 1 gives dp[4] + 1 = 2, the coin 3 gives dp[2] + 1 = 3, and the coin 4 gives dp[1] + 1 = 2; the tie goes to the coin tried first, so last[5] is 1. For dp[6] the coin 3 gives dp[3] + 1 = 2, beating 3 from the other coins. The table reads 0 1 2 1 1 2 2. Walking back, last[6] = 3 leads to amount 3, and last[3] = 3 leads to 0, so the answer is 3 + 3. Greedy would have taken 4 + 1 + 1, three coins.
The page lets you type your own coins and set the amount from 4 to 20. Try coins 2 and 4 with amount 7: every odd amount stays at infinity, so dp[7] is never filled and the page returns -1. Any amount the coins cannot reach shows up in the table the same way.
Time: each of the amount + 1 slots tries every coin once. Space: the dp and last arrays each hold one entry per amount from 0 to the target.