Skip to lesson

The coin change problem illustrates both optimization and counting dynamic programming, demonstrating the deep impact of loop ordering.

Fewest coins: Minimization with unbounded choices

Coin change is the problem of finding the fewest coins, or the number of ways, that add up to a target amount when every coin value can be used any number of times.

The fewest coins problem seeks the minimum number of coins to assemble a target amount. Greedy choices fail because choosing the largest coin can strand subproblems in suboptimal paths. Dynamic programming systematically evaluates every coin denomination for each target.

Step by step

Step 1 of 5

Array: 0, 7, 7, 7, 7, 7, 7.
amt
0
coins
0
Initialize dp table for target 6 with sentinel 7. dp[0] = 0.

Example 1 · Fewest Coins, Plain Recursion: Exponential Time

CoinRecursion.javaJava
public class CoinRecursion {    static int calls = 0;
    public static int fewest(int[] coins, int amount) {        calls++;        if (amount == 0) return 0;        int best = Integer.MAX_VALUE;        for (int coin : coins) {            if (coin <= amount) {                int sub = fewest(coins, amount - coin);                if (sub != Integer.MAX_VALUE) best = Math.min(best, sub + 1);            }        }        return best;    }
    public static void main(String[] args) {        int[] coins = {1, 2, 5};        int answer = fewest(coins, 11);        System.out.println("Coins for 11: " + (answer == Integer.MAX_VALUE ? -1 : answer));        System.out.println("Calls made: " + calls);    }}
Output
Coins for 11: 3
Calls made: 527

What this code does

  • Each call tries every coin, so the tree of calls grows exponentially with the amount.
  • The same remaining amount, such as 6, is reached through many different coin orders and solved again each time.
  • Even this small amount of 11 needs 527 calls.

Example 2 · Fewest Coins, Memoization: O(amount x coins) Time, O(amount) Space

CoinMemo.javaJava
import java.util.Arrays;
public class CoinMemo {    static int calls = 0;
    public static int fewest(int[] coins, int amount, int[] memo) {        calls++;        if (amount == 0) return 0;        if (memo[amount] != -1) return memo[amount];        int best = Integer.MAX_VALUE;        for (int coin : coins) {            if (coin <= amount) {                int sub = fewest(coins, amount - coin, memo);                if (sub != Integer.MAX_VALUE) best = Math.min(best, sub + 1);            }        }        memo[amount] = best;        return best;    }
    public static void main(String[] args) {        int[] coins = {1, 2, 5};        int[] memo = new int[12];        Arrays.fill(memo, -1);        int answer = fewest(coins, 11, memo);        System.out.println("Coins for 11: " + (answer == Integer.MAX_VALUE ? -1 : answer));        System.out.println("Calls made: " + calls);    }}
Output
Coins for 11: 3
Calls made: 29

What this code does

  • memo[amount] stores the best answer for that amount; -1 means not computed yet.
  • There are only 11 different amounts, each tried with 3 coins, so calls fall from 527 to 29.
  • The cost is one memo cell per amount plus recursion depth up to the amount.

Example 3 · Fewest Coins, Tabulation: O(amount x coins) Time, O(amount) Space

CoinChangeFewest.javaJava
import java.util.Arrays;
public class CoinChangeFewest {    public static int coinChange(int[] coins, int amount) {        int max = amount + 1;        int[] dp = new int[amount + 1];        Arrays.fill(dp, max);        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {            for (int coin : coins) {                if (coin <= i) {                    dp[i] = Math.min(dp[i], dp[i - coin] + 1);                }            }        }        return dp[amount] > amount ? -1 : dp[amount];    }
    public static void main(String[] args) {        int[] coins1 = {1, 2, 5};        System.out.println("Coins for 11: " + coinChange(coins1, 11));        int[] coins2 = {2};        System.out.println("Coins for 3: " + coinChange(coins2, 3));        int[] coins3 = {1};        System.out.println("Coins for 0: " + coinChange(coins3, 0));    }}
Output
Coins for 11: 3
Coins for 3: -1
Coins for 0: 0

What this code does

  • Optimal order of work: the loop fills amounts from 1 upwards, so every smaller answer is ready and no recursion is needed.
  • Table initialized with amount + 1 avoids integer overflow during addition.
  • Base case dp[0] equals 0, seeding bottom-up transitions.

Define dp[i] as the minimum coins needed to make amount i. Initialize all cells with amount + 1, representing an unreachable infinity sentinel. Set base case dp[0] = 0, because zero coins are needed to make zero cents. For each amount i from 1 to target, try subtracting every coin denomination. If coin <= i, candidate cost is dp[i - coin] + 1. Take the minimum over all valid coins. If dp[target] exceeds target at the end, return negative one to signal impossibility.

Loop order: Combinations versus permutations

When counting ways to make change, loop nesting order fundamentally dictates the mathematical result. If coins loop on the outside, you count combinations where element order does not matter. Set {1, 2} and set {2, 1} are treated as identical groupings.

Example 4 · Coin Change Total Combinations

CoinChangeCombinations.javaJava
public class CoinChangeCombinations {    public static int change(int amount, int[] coins) {        int[] dp = new int[amount + 1];        dp[0] = 1;
        for (int coin : coins) {            for (int i = coin; i <= amount; i++) {                dp[i] += dp[i - coin];            }        }        return dp[amount];    }
    public static void main(String[] args) {        int[] coins = {1, 2, 5};        System.out.println("Combinations for 5: " + change(5, coins));        int[] coins2 = {2};        System.out.println("Combinations for 3: " + change(3, coins2));    }}
Output
Combinations for 5: 4
Combinations for 3: 0

What this code does

  • Outer loop iterates over coins, preventing duplicate permutation orderings.
  • Inner loop moves forward from coin to amount for unbounded coin reuse.
  • For target 5 with {1, 2, 5}, the 4 combinations are {5}, {1,2,2}, {1,1,1,2}, and {1,1,1,1,1}.

Example 5 · Coin Change Ordered Permutations

CoinChangePermutations.javaJava
public class CoinChangePermutations {    public static int combinationSum4(int[] nums, int target) {        int[] dp = new int[target + 1];        dp[0] = 1;
        for (int i = 1; i <= target; i++) {            for (int num : nums) {                if (i - num >= 0) {                    dp[i] += dp[i - num];                }            }        }        return dp[target];    }
    public static void main(String[] args) {        int[] nums = {1, 2, 3};        System.out.println("Permutations for 4: " + combinationSum4(nums, 4));        int[] nums2 = {9};        System.out.println("Permutations for 3: " + combinationSum4(nums2, 3));    }}
Output
Permutations for 4: 7
Permutations for 3: 0

What this code does

  • Outer loop iterates over amounts, allowing any coin to serve as the final step.
  • Different orderings like (1, 3) and (3, 1) are counted as distinct paths.
  • Target 4 yields 7 distinct ordered sequences using coins {1, 2, 3}.

Outer loop over coins enforces that each coin is considered in a fixed chronological order. A coin cannot be reintroduced after later denominations have already been processed. This prevents duplicate order permutations from entering the accumulated sum. Conversely, placing the amount loop on the outside counts permutations where order matters. Every coin can be picked as the final step leading into current amount i. Consequently, sequence [1, 2] and sequence [2, 1] count as two separate ways.

Unbounded versus 0/1 knapsack inner loop directions

The direction of the inner loop determines whether items can be reused indefinitely. In unbounded coin change, you can reuse each coin an unlimited number of times. Therefore, the inner loop iterates forward from coin up to amount. Forward iteration allows cell i to build directly on earlier updates made at cell i - coin.

In zero-one knapsack problems, each item can be selected at most once. To prevent an item from being reused within the same step, iterate backward from amount down to coin. Backward iteration ensures cell i references the state before the current item was considered.

Mastering forward versus backward iteration prevents accidental multiple usage of single-use items. This distinction separates unbounded problems from bounded 0/1 knapsack variants.

Find the bug

Find the wrong line

Each method has one wrong line. Tap it, then check.

Fewest coins, each coin can be reused. Which line breaks the answer?

Round 1 of 3

Next step

Check your understanding

10 quick questions