1. Impossible sentinel
Unknown totals start as impossible.
Array(amount + 1).fill(Infinity)Typorithm · medium
Step 1 of 8 · intro card
Dynamic Programming
Coin Change stores the fewest coins needed for every amount up to the target.
Each amount is a subproblem.
For every amount, try every coin that fits.
Infinity marks amounts that cannot yet be formed.
State: min coins for total.
Base: dp[0] = 0.
Transition: min(existing, dp[total-coin] + 1).
Return -1 if target stays impossible.
function coinChange(coins, amount) {
const dp = Array(amount + 1).fill(Infinity);
dp[0] = 0;
for (let total = 1; total <= amount; total++) {
for (const coin of coins) {
if (coin <= total) {
dp[total] = Math.min(dp[total], dp[total - coin] + 1);
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount];
}Connect each part of the code to the concept before you type.
Unknown totals start as impossible.
Array(amount + 1).fill(Infinity)Zero coins are needed to make amount 0.
dp[0] = 0Each total can be reached by taking any valid coin.
for (const coin of coins)Take one coin plus the best way to make the remaining amount.
dp[total] = Math.min(dp[total], dp[total - coin] + 1)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputCoins 1,3,4 · amount 6
Follow temporary values, local state and supporting structures at this step.
↗ The 7-cell working table above is itself auxiliary memory. Input values are shown separately.
Input · not auxiliary memory
Coins3 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state