Understanding Coin Change
Given positive coin denominations and an amount, return the fewest coins needed to make that amount. Coins may be reused. Return −1 if no combination exists.
How it works
The best answer for amount a can be built from the best answer for a − coin, plus one coin.
Define dp[a] as the fewest coins for amount a. Start with dp[0] = 0 and all other states unreachable. For every amount, try each coin and keep the minimum.
Try an example
Input: coins = [1, 2, 5], amount = 11
Output: 3
5 + 5 + 1 uses three coins.
Input: coins = [2], amount = 3
Output: -1
An odd amount cannot be made from only 2-value coins.
Constraints
- Coin denominations are distinct positive integers.
- Amount 0 requires zero coins.
- Visualization limits: 12 denominations and amount at most 100.
Use the simulator
Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.
Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.