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
PHP DSA Implementation
basic.php
<?php
function list_string($values) { return "[" . implode(", ", $values) . "]"; }
$coins = [1, 3, 4];
$target = 6;
$inf = $target + 1;
$dp = array_fill(0, $target + 1, $inf);
$dp[0] = 0;
for ($amount = 1; $amount <= $target; $amount++) {
foreach ($coins as $coin) {
if ($amount >= $coin) {
$candidate = $dp[$amount - $coin] + 1;
if ($candidate < $dp[$amount]) $dp[$amount] = $candidate;
}
}
}
echo $dp[$target] . PHP_EOL;
echo list_string($dp) . PHP_EOL;
?>
Implementation notes
- The checked PHP values are
$coins = [1, 3, 4]and$target = 6. $inf = $target + 1sets the unreachable sentinel to7for this run.$dp = array_fill(0, $target + 1, $inf)creates seven slots, then$dp[0] = 0gives the trace start[0, 7, 7, 7, 7, 7, 7].- The outer loop scans
$amountfrom1through6; the innerforeach ($coins as $coin)tries coins in1, 3, 4order. if ($amount >= $coin)is the bounds guard before reading$dp[$amount - $coin].$candidate = $dp[$amount - $coin] + 1computes the candidate count, andif ($candidate < $dp[$amount])writes only improvements.- The trace writes
dp[1]=1,dp[2]=2,dp[3]=1, anddp[4]=1. - For amount
5, coin1and coin4both give2, sodp[5]ends as2. - For amount
6, coin3gives the best candidate2, so the final table is[0, 1, 2, 1, 1, 2, 2]. - The code does not convert the sentinel to
-1; this pinned target is reachable, soecho $dp[$target] . PHP_EOLprints2, then the full table.
Output
2
[0, 1, 2, 1, 1, 2, 2]