Start learning free

LESSON 245 OF 314 · DYNAMIC PROGRAMMING

Coin Change in C#: Bottom-Up Dynamic Programming, O(n · amount)

Practice O(n · amount) Read the full explanation

You get an array coins of coin values and an integer amount.

Return the smallest number of coins that add up to exactly amount.

You can use each coin value as many times as you like. If no mix of coins makes amount, return -1.

 

Example 1:

Input: coins = [2, 5, 10], amount = 27
Output: 4
Explanation: 27 = 10 + 10 + 5 + 2.
No three coins add up to 27.

Example 2:

Input: coins = [4, 6], amount = 9
Output: -1
Explanation: Both coin values are even.
So every sum of them is even.
9 is odd, so no mix of coins makes it.

Example 3:

Input: coins = [1, 5, 6, 9], amount = 11
Output: 2
Explanation: 11 = 5 + 6.
9 + 1 + 1 also makes 11, but that is three coins.

 

Constraints:

  • coins holds 1 to 12 values.
  • Each value is from 1 to 231 - 1.
  • amount is from 0 to 10,000.
  • For amount = 0, the answer is 0 (no coins are needed).
STEP 1 OF 8
    Ctrl + Enter to check

    C# · DYNAMIC PROGRAMMING

    Coin Change in C#, explained

    Problem overview

    CoinChange receives an int[] of coin values and an int named amount. It returns the fewest coins that add up to exactly amount, or -1 when no combination works. Every coin value may be used any number of times.

    With coins {1, 2, 5} and amount 11 the answer is 3 (5 + 5 + 1). With {2} and amount 3 it is -1, since 2s only make even sums. With {1, 3, 4} and amount 6 it is 2 (3 + 3). Amount 0 needs no coins, so it returns 0.

    Approach: the best answer for every smaller sum

    Always taking the largest coin that fits looks tempting but is wrong: for {1, 3, 4} and 6 it picks 4 + 1 + 1, three coins, while 3 + 3 uses two. Trying every combination is far too slow, because coins can repeat.

    Instead, let dp[i] be the fewest coins that make the sum i. If the last coin added is coin, the coins before it make i - coin, so dp[i] is dp[i - coin] + 1. Trying every coin as the last one and keeping the smallest gives dp[i]. Every entry reuses answers for smaller sums, so filling the table from 1 up to amount works.

    Sums that can't be made need a marker. Every coin is worth at least 1, so no sum i ever needs more than i coins. A value of amount + 1 can therefore never be a real answer, and it works as "impossible so far". It also behaves well in the formula: when i - coin can't be made, dp[i - coin] + 1 is above amount too, and it never beats a real answer.

    A plain recursion that tries every coin from every remaining sum would solve the same sums again and again, and its running time grows exponentially with the amount. The table solves each sum exactly once, which is what turns the problem into a pair of nested loops.

    Step by step

    1. Create dp with amount + 1 entries, indexes 0 to amount, and fill every entry with amount + 1 using Array.Fill. A new int array holds zeros, so the fill is needed.
    2. Set dp[0] = 0. The sum 0 takes no coins, and every other sum is built on it.
    3. Loop i from 1 to amount inclusive. By the time the loop reaches i, all smaller sums are done.
    4. Loop over the coins with foreach. Each coin is tried as the last one added.
    5. Check coin <= i. A bigger coin doesn't fit, and i - coin would be a negative index.
    6. Update dp[i] to Math.Min(dp[i], dp[i - coin] + 1).
    7. If dp[amount] > amount, return -1. Only a sum that no combination makes keeps its starting value.
    8. Otherwise return dp[amount].

    For coins {1, 3, 4} and amount 6, the table ends as:

    dp = 0 1 2 1 1 2 2

    Here dp[6] is 2. For coins {2} and amount 3 the table ends as 0 4 1 4: the sum 3 still holds its marker 4, which is more than 3, so the method returns -1.

    Walking through coins 1, 2, 5 and amount 11

    For coins {1, 2, 5} and amount 11 the finished table is:

    dp = 0 1 1 2 2 1 2 2 3 3 2 3

    Entry 11 is the minimum of three candidates, one per coin. Coin 1 gives dp[10] + 1 = 3, coin 2 gives dp[9] + 1 = 4, and coin 5 gives dp[6] + 1 = 3. The smallest is 3, which matches 5 + 5 + 1. Notice that the table never records which coins were used, only how many. That is all the problem asks for.

    The solution in C#

    class Solution {
        public int CoinChange(int[] coins, int amount) {
            int[] dp = new int[amount + 1];
            Array.Fill(dp, amount + 1);
            dp[0] = 0;
            for (int i = 1; i <= amount; i++) {
                foreach (int coin in coins) {
                    if (coin <= i) {
                        dp[i] = Math.Min(dp[i], dp[i - coin] + 1);
                    }
                }
            }
            if (dp[amount] > amount) return -1;
            return dp[amount];
        }
    }
    

    Details worth knowing:

    • Array.Fill. Array.Fill(dp, value) sets every element of an array to one value. It is in System.
    • Why not int.MaxValue as the marker? dp[i - coin] + 1 would then overflow and wrap to a large negative number, which Math.Min would pick as the "best" answer. The marker amount + 1 is small enough to add 1 to safely.
    • Large coin values. A coin can be as large as int.MaxValue. The check coin <= i keeps it out of the formula, so with coins {2147483647} and amount 10000 the method returns -1 without any problem.
    • foreach over an array reads each element in order; the loop variable coin can't be assigned to.

    Complexity

    Let n be the number of coins.

    Time: O(n · amount). The outer loop runs amount times and the inner one n times, with constant work inside.

    Space: O(amount) for the dp table.

    Edge cases and common mistakes

    • Amount 0. The loops don't run, and the method returns dp[0], which is 0, for any coins.
    • Coins bigger than the amount. {5, 10} with amount 3 returns -1.
    • Forgetting the coin <= i check. It leads to a negative index and an IndexOutOfRangeException.
    • Returning dp[amount] unconditionally. An impossible amount would return amount + 1 instead of -1.
    • Greedy choice. Taking the largest coin first fails for {1, 3, 4} and 6.
    • Leaving the table at zeros. Every sum would look makeable with 0 coins, and the answers would all be 0.

    Testing

    • Coins {1, 2, 5}, amount 11 gives 3.
    • Coins {2}, amount 3 gives -1.
    • Coins {1, 3, 4}, amount 6 gives 2.
    • Coins {1}, amount 0 gives 0.
    • Coins {5, 10}, amount 3 gives -1.
    • Coins {186, 419, 83, 408}, amount 6249 gives 20.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free