Maintained by Vikas Dulgunde, software engineer
You are handed a list of coin denominations and a target amount. Each denomination can be picked as many times as you like, and there is no limit on how many coins you spend. Your job is to hit the target exactly while using the smallest possible number of coins.
When several different mixes of coins all reach the target, only the count matters, so you want the mix with the fewest pieces. The specific coins chosen are not part of the answer.
If there is no way to land on the amount at all, return -1. An amount of zero is always reachable with zero coins, so that case answers 0.
5 + 5 + 1 sums to 11 with 3 coins. No two-coin combination reaches 11, so 3 is the minimum.
Every sum built from 2s is even, so an odd target like 3 can never be reached. The answer is -1.
10 + 10 + 5 + 2 reaches 27 with 4 coins, and no three coins from this set sum to 27.
Visible test cases
Picking the largest coin that fits at each step (a greedy choice) can overshoot the optimal count. With coins [1, 5, 11] and amount 15, grabbing 11 first leads to 11 + 1 + 1 + 1 + 1 = 5 coins, but 5 + 5 + 5 = 3 coins is better. You need to consider every coin at every sub-amount.
Define best[x] as the fewest coins that make exactly x. Then best[x] is 1 plus the smallest best[x - coin] over every coin that is not larger than x.
Build best from 0 up to amount so each value you need has already been computed. Start best[0] = 0 and mark every other entry as unreachable until a coin proves otherwise.
Try every denomination at each remaining amount and recurse on what is left, taking the cheapest branch. Memoize on the remaining amount so repeated sub-amounts are solved once.
Fill a table best[0..amount] where best[x] is the minimum coins for x. Each entry is one more than the best of its reachable predecessors best[x - coin].