Visualizers
Coin Change Visualizer
Animate finding the minimum coins for a target amount using a 1D DP array.
native
Client-side
Ready to compute.
Execution Log
Min Coins Needed: -
Coins Chosen: -
Current Action:
Idle
Legend:
Uncomputed
Active Lookups
Calculated Value
Backtrack Path
Coin Change DP Algorithm
The Coin Change problem is a classic dynamic programming problem. Given coins of different denominations and a total target amount, find the minimum number of coins that make up that amount. If that amount of money cannot be made up, return -1.
Dynamic Programming Relation
We maintain a 1D DP table `dp[i]` representing the minimum coins needed for amount $i$:
- Base Case: `dp[0] = 0` (0 coins to make amount 0)
- Relation: `dp[i] = min(dp[i], dp[i - coin] + 1)` for each coin where `coin <= i`
Implementation
function coinChange(coins, amount) {
const dp = Array(amount + 1).fill(Infinity);
dp[0] = 0;
for (let i = 1; i <= amount; i++) {
for (const coin of coins) {
if (i - coin >= 0) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount];
}