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
Java DSA Implementation
Basic.java
import java.util.Arrays;
public class Basic {
static String listString(int[] values) {
StringBuilder out = new StringBuilder("[");
for (int i = 0; i < values.length; i++) {
if (i > 0) out.append(", ");
out.append(values[i]);
}
return out.append("]").toString();
}
public static void main(String[] args) {
int[] coins = {1, 3, 4};
int target = 6;
int inf = target + 1;
int[] dp = new int[target + 1];
Arrays.fill(dp, inf);
dp[0] = 0;
for (int amount = 1; amount <= target; amount++) {
for (int coin : coins) {
if (amount >= coin) {
int candidate = dp[amount - coin] + 1;
if (candidate < dp[amount]) dp[amount] = candidate;
}
}
}
System.out.println(dp[target]);
System.out.println(listString(dp));
}
}
Output
2
[0, 1, 2, 1, 1, 2, 2]
Implementation notes
- Java stores both
coinsanddpin primitiveint[]arrays.dpis one contiguous array oftarget + 1slots, so updates mutate indexed integer cells in place. - The unreachable sentinel is
inf = target + 1, andArrays.fill(dp, inf)initializes every amount beforedp[0] = 0writes the base case. - The loop order is amount-first, then coin:
amountruns from1throughtarget, and the enhancedfor (int coin : coins)tries each transition only whenamount >= coin. candidate = dp[amount - coin] + 1reads an earlier computed cell, which may still hold the sentinel in general; because the sentinel is only7here, adding one cannot approachintoverflow.if (candidate < dp[amount])then writes the smaller primitive value back into the samedparray.- The replay-visible table moves from
[0, 7, 7, 7, 7, 7, 7]to[0, 1, 2, 1, 1, 2, 2]. Allocation is mainly the two arrays plus theStringBuilder, its backing storage, and the returnedStringused for deterministic output, all managed by JVM GC.