Start learning free

LESSON 245 OF 314 · DYNAMIC PROGRAMMING

Coin Change in Rust: Bottom-Up Dynamic Programming in 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

    RUST · DYNAMIC PROGRAMMING

    Coin Change in Rust, explained

    Problem overview

    The function coin_change receives a vector of coin values, coins, and an amount. It returns the fewest coins that add up to exactly amount, or -1 if no combination does. Each coin value can be used any number of times, and an amount of 0 needs 0 coins.

    With coins = [1, 2, 5] and amount = 11 the answer is 3, from 5 + 5 + 1. With coins = [2] and amount = 3 it is -1, since coins of 2 only make even sums.

    Approach: the fewest coins for every smaller sum

    The tempting shortcut is greedy: always take the largest coin that fits. It fails. For coins = [1, 3, 4] and amount = 6, greedy takes 4 + 1 + 1, three coins, while 3 + 3 uses two.

    Dynamic programming avoids guessing. 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 that choice costs dp[i - coin] + 1. Trying every coin as the last one and keeping the smallest result gives dp[i]. Filling the table from small sums to large guarantees that dp[i - coin] is ready when it's needed.

    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, and amount + 1 can never be a real answer. The table starts filled with amount + 1, meaning "can't make it (yet)". An unreachable sum keeps that value, and a sum built on an unreachable one gets a value above amount too, so the marker never looks like a real result.

    For coins = [1, 3, 4] and amount = 6, the table fills as:

    dp[1] = 1
    dp[2] = 2
    dp[3] = 1
    dp[4] = 1
    dp[5] = 2
    dp[6] = 2

    so the answer is dp[6] = 2.

    Step by step

    1. Create dp with vec![amount + 1; amount as usize + 1]. It has one entry per sum from 0 to amount, all set to the "impossible" marker. Sizes are usize in Rust, so amount is converted with as usize, while the entries stay i32.
    2. Set dp[0] = 0. The sum 0 takes no coins, and every other sum builds on it.
    3. Loop over the sums with for i in 1..=amount as usize. The end is included. When amount is 0 the range is empty and nothing runs.
    4. Loop over the coins with for &coin in &coins. Borrowing &coins keeps the vector usable, and the pattern &coin copies each value out of the reference.
    5. Check that the coin fits with (coin as usize) <= i. A coin larger than i would make i - coin negative. Rust doesn't compare an i32 with a usize, so the coin is converted first.
    6. Update the entry with dp[i] = dp[i].min(dp[i - coin as usize] + 1): keep the better of the current value and "the best way to make i - coin, plus this coin".
    7. Return -1 if dp[amount as usize] is still above amount. Only a sum that no combination makes keeps the marker.
    8. Otherwise return dp[amount as usize] with no semicolon. For amount = 0 that is dp[0], which is 0.

    The solution in Rust

    impl Solution {
        fn coin_change(coins: Vec<i32>, amount: i32) -> i32 {
            let mut dp = vec![amount + 1; amount as usize + 1];
            dp[0] = 0;
            for i in 1..=amount as usize {
                for &coin in &coins {
                    if (coin as usize) <= i {
                        dp[i] = dp[i].min(dp[i - coin as usize] + 1);
                    }
                }
            }
            if dp[amount as usize] > amount {
                return -1;
            }
            dp[amount as usize]
        }
    }
    

    The Rust details worth a closer look:

    • vec![value; count] builds a vector with count copies of value.
    • Casts and precedence. as binds tighter than + and than the comparison operators, so amount as usize + 1 means (amount as usize) + 1. The parentheses in (coin as usize) <= i make that order visible. They would be required with a plain <: the compiler reads < after as usize as the start of generic arguments and reports an error.
    • Casting a positive i32 to usize is exact. Coins and amounts here are never negative. A negative value cast with as usize wraps silently to a huge number: -1_i32 as usize is 18446744073709551615.
    • Large coins are safe. A coin as big as 2147483647 is simply skipped by the if for every sum up to 10,000. The check happens before the subtraction, so i - coin as usize can never underflow.
    • The marker can't overflow. Entries stay at most amount + 1 plus 1 when read, far below the i32 limit for amount <= 10000.
    • min is a method on integers: a.min(b) returns the smaller one.
    • Early return and the final expression. The return -1; inside the if needs the keyword and a semicolon. The last line, dp[amount as usize], has no semicolon and is the value returned otherwise.

    Complexity

    Time: O(n · amount), where n is the number of coins. The outer loop runs amount times and the inner loop n times, with constant work for each pair.

    Space: O(amount). The table has amount + 1 entries.

    Edge cases and common mistakes

    • Amount 0. The loops don't run and the function returns dp[0], which is 0. coins = [1] with amount = 0 gives 0.
    • Unreachable amounts. [2] with 3 gives -1: the table ends as [0, 4, 1, 4], and the last entry is above 3.
    • Every coin too large. [5, 10] with 3 gives -1, and [2147483647] with 5 gives -1.
    • Greedy thinking. [1, 3, 4] with 6 gives 2, not 3.
    • Starting the table at 0. If every entry began at 0, min would keep 0 and every sum would look free. The starting value must be larger than any real answer.
    • Using 0 or -1 as the marker. Adding 1 to a marker of -1 would produce 0, which looks like a valid result and corrupts later entries. A large marker stays large when you add 1.
    • Forgetting the coin <= i check. The index i - coin would go below zero, which a usize can't hold: a debug build panics on the subtraction, and an optimized build wraps to a huge index that panics when used.

    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 = [2], amount = 4 gives 2.
    • coins = [3, 7], amount = 11 gives -1.
    • coins = [186, 419, 83, 408], amount = 6249 gives 20.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free