Video in progress

Strong Middle 🧠 Problem solving

When counting the ways to make a sum from coins, why does the order of the loops change the result?

If the outer loop is over coins, each combination is counted once (1+2 and 2+1 are the same). If the outer loop is over the sum, different orders are counted separately, which gives the number of sequences. The two pieces of code look almost identical, which makes this a classic trap.

📖 Answer

The problem: coins {1, 2, 5}, sum 5. How many ways? As combinations, the answer is 4: 5, 2+2+1, 2+1+1+1, 1+1+1+1+1.

// Combinations — order doesn't matter
static long combinations(int[] coins, int amount) {
    long[] dp = new long[amount + 1];
    dp[0] = 1;
    for (int c : coins)                       // outer — the coin
        for (int s = c; s <= amount; s++)
            dp[s] += dp[s - c];
    return dp[amount];
}

// Sequences — 1+2 and 2+1 count separately
static long orderedWays(int[] coins, int amount) {
    long[] dp = new long[amount + 1];
    dp[0] = 1;
    for (int s = 1; s <= amount; s++)         // outer — the sum
        for (int c : coins)
            if (c <= s) dp[s] += dp[s - c];
    return dp[amount];
}

The second one returns 9 for the same input.

Why? In the first version we add coins in a fixed order: when we're considering the coin 2, dp contains only sums made of 1s. That's why each combination appears in just one form. In the second one, for each sum we ask "which coin was the last one?", and that counts sequences.

The inner loop goes upward because you can take any number of each coin. The backward loop from 0/1 knapsack isn't needed here.

For the minimum number of coins, the order doesn't matter: dp[s] = min(dp[s], dp[s - c] + 1), with the initial value "infinity". If you make it Integer.MAX_VALUE, the + 1 overflows and turns negative; taking amount + 1 as "infinity" is safer.

The answer grows fast, so many problems ask for the result mod 1_000_000_007. Don't forget to apply % after every addition.