Recursion and Dynamic Programming
Coin Change (Bottom-Up)
Build a one-dimensional table where each amount stores the fewest coins needed to make it.
Algorithm
Steps
- Initialize
dp[0] = 0and all other amounts to an unreachable sentinel. - Scan amounts from
1through6. - For each coin, read the earlier cell
dp[amount - coin]when it exists. - Write the smallest candidate into the current amount.
- Print both the final answer and the full DP array.
Complexity
- Time: O(target * coin_count)
- Space: O(target)
bottom-up dynamic programming
`dp[a]` is solved from already-computed smaller amounts, so every table cell has a visible dependency.
Visual walkthrough
JavaScript DSA Implementation
basic.js
function listString(values) { return `[${values.join(", ")}]`; }
const coins = [1, 3, 4];
const target = 6;
const inf = target + 1;
const dp = Array(target + 1).fill(inf);
dp[0] = 0;
for (let amount = 1; amount <= target; amount++) {
for (const coin of coins) {
if (amount >= coin) {
const candidate = dp[amount - coin] + 1;
if (candidate < dp[amount]) dp[amount] = candidate;
}
}
}
console.log(dp[target]);
console.log(listString(dp));
Output
2
[0, 1, 2, 1, 1, 2, 2]
Implementation notes
- JavaScript stores
coinsanddpasArrayobjects containingNumbervalues. The unreachable sentinel is the finite valuetarget + 1, so this checked-in run uses7rather thanInfinity. Array(target + 1).fill(inf)initializes every slot to7, thendp[0] = 0seeds the base case. The algorithm mutates the samedparray in place.- The outer loop scans
amountfrom1throughtarget; the innerfor...ofloop tries coins[1, 3, 4]in that order.amount >= coinguards the lookupdp[amount - coin]. - Candidates are numeric additions,
dp[amount - coin] + 1, and the update is an explicit minimum check:if (candidate < dp[amount]) dp[amount] = candidate. - The replayed table states are
[0, 7, 7, 7, 7, 7, 7], then[0, 1, 7, 7, 7, 7, 7],[0, 1, 2, 7, 7, 7, 7],[0, 1, 2, 1, 7, 7, 7],[0, 1, 2, 1, 1, 7, 7],[0, 1, 2, 1, 1, 2, 7], and[0, 1, 2, 1, 1, 2, 2]. console.log(dp[target])prints2, thenlistString(dp)prints the final table. Visible allocation is the coins array, DP array, and output strings; the nested loops only update scalar bindings and DP slots.