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
TypeScript DSA Implementation
basic.ts
function listString(values: number[]): string { 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
- In TypeScript,
coinsis inferred asnumber[]from[1, 3, 4]andtargetis the numeric literal6. The checked source usesArray(target + 1).fill(inf), sodpis inferred from the bareArrayconstructor rather than an explicitnumber[]annotation. infistarget + 1, soArray(target + 1).fill(inf)creates seven slots initialized to sentinel7, thendp[0] = 0mutates the base case.- The outer loop advances
amountfrom1through6; the innerfor (const coin of coins)only readsdp[amount - coin]whenamount >= coin. - Updates use
const candidate = dp[amount - coin] + 1and an explicitcandidate < dp[amount]comparison rather thanMath.min. - The trace records table mutations from
[0, 7, 7, 7, 7, 7, 7]through[0, 1, 2, 1, 1, 2, 2], with amount6writingdp[6] = 2from coin3. - The two
console.logcalls print2and the full table string. Visible allocation is thecoinsarray literal, the DP array, and the output string; mutation is limited to numericdpcells.