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
C DSA Implementation
basic.c
#include <stdio.h>
void print_list(int values[], int count) {
printf("[");
for (int i = 0; i < count; i++) {
if (i > 0) printf(", ");
printf("%d", values[i]);
}
printf("]\n");
}
int main(void) {
int coins[] = {1, 3, 4};
int target = 6;
int inf = target + 1;
int dp[7];
for (int i = 0; i <= target; i++) dp[i] = inf;
dp[0] = 0;
for (int amount = 1; amount <= target; amount++) {
for (int i = 0; i < 3; i++) {
int coin = coins[i];
if (amount >= coin) {
int candidate = dp[amount - coin] + 1;
if (candidate < dp[amount]) dp[amount] = candidate;
}
}
}
printf("%d\n", dp[target]);
print_list(dp, 7);
return 0;
}
Output
2
[0, 1, 2, 1, 1, 2, 2]
Implementation notes
- C stores
coinsas stack arrayint coins[] = {1, 3, 4}and the DP table as fixed stack arrayint dp[7]for amounts0..6. int inf = target + 1gives sentinel value7; the code initializes everydp[i]to that sentinel, then setsdp[0] = 0.- The outer loop scans
amount = 1..target, and the inner loop uses literali < 3to readcoins[i]; there is no helper call or array parameter decay in the DP update itself. - When
amount >= coin, the source computescandidate = dp[amount - coin] + 1and mutatesdp[amount]only if the candidate is smaller. It does not add a separatedp[...] != infguard; the checked sentinel and target are small enough thatintoverflow is not a runtime concern here. - The trace records DP states from
[0, 7, 7, 7, 7, 7, 7]through[0, 1, 2, 1, 1, 2, 2], with amount6choosing the coin3candidate2. printf("%d\n", dp[target])prints the answer, thenprint_list(dp, 7)prints the full table.print_list(int values[], int count)receives the array as a pointer after parameter decay and formats each integer withprintf.