Example 1
- Input
- coins = [1, 2], amount = 3
- Output
- 2
The sequences [1, 2] and [2, 1] use two coins, whereas [1, 1, 1] uses three. No denomination equals 3, so one coin cannot suffice.
Given coin denominations with unlimited supply, find the smallest number of coins that sums to amount, or -1 when the amount cannot be formed.
Given positive denominations in coins and a target amount, choose as many copies of each denomination as needed. Return the minimum number of coins whose total is exactly the target. Return -1 if no choice reaches it. Return zero for amount zero.
Coin order does not change a combination, and the input array remains unchanged.
The sequences [1, 2] and [2, 1] use two coins, whereas [1, 1, 1] uses three. No denomination equals 3, so one coin cannot suffice.
Every total made from copies of 2 is even, so the odd target 3 is unreachable.
The empty selection already totals zero. Adding any positive coin would exceed the target.
The selection [5, 5, 1] reaches 11 with three coins. Two coins total at most 10, so three is minimal.
Two copies of 3 reach 6. Taking the largest coin 4 first would require two further 1s, showing why greedy choice fails.
Remove one coin from a solution and what remains is a smaller version of the same problem. With denominations [1, 2] and target 3, choosing 1 leaves remainder 2, while choosing 2 leaves remainder 1. Both continuations need one more coin, so the answer is two. Searching every coin order repeats these remainders; a table can instead solve each amount once. Largest-first greedy choices are unsafe: [1, 3, 4] and target 6 need two 3s, while taking 4 first needs three coins.
Reveal Recursive Coin Search: intuition, complexity, and code
An unlimited-choice minimum can be expressed as one choice plus an optimal smaller capacity. Once positive choices make dependencies strictly smaller, increasing-capacity dynamic programming replaces a repeated search with one calculation per state.