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
- Create
dpwithvec![amount + 1; amount as usize + 1]. It has one entry per sum from 0 toamount, all set to the "impossible" marker. Sizes areusizein Rust, soamountis converted withas usize, while the entries stayi32. - Set
dp[0] = 0. The sum 0 takes no coins, and every other sum builds on it. - Loop over the sums with
for i in 1..=amount as usize. The end is included. Whenamountis 0 the range is empty and nothing runs. - Loop over the coins with
for &coin in &coins. Borrowing&coinskeeps the vector usable, and the pattern&coincopies each value out of the reference. - Check that the coin fits with
(coin as usize) <= i. A coin larger thaniwould makei - coinnegative. Rust doesn't compare ani32with ausize, so the coin is converted first. - 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 makei - coin, plus this coin". - Return -1 if
dp[amount as usize]is still aboveamount. Only a sum that no combination makes keeps the marker. - Otherwise return
dp[amount as usize]with no semicolon. Foramount = 0that isdp[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 withcountcopies ofvalue.- Casts and precedence.
asbinds tighter than+and than the comparison operators, soamount as usize + 1means(amount as usize) + 1. The parentheses in(coin as usize) <= imake that order visible. They would be required with a plain<: the compiler reads<afteras usizeas the start of generic arguments and reports an error. - Casting a positive
i32tousizeis exact. Coins and amounts here are never negative. A negative value cast withas usizewraps silently to a huge number:-1_i32 as usizeis 18446744073709551615. - Large coins are safe. A coin as big as 2147483647 is simply skipped by the
iffor every sum up to 10,000. The check happens before the subtraction, soi - coin as usizecan never underflow. - The marker can't overflow. Entries stay at most
amount + 1plus 1 when read, far below thei32limit foramount <= 10000. minis a method on integers:a.min(b)returns the smaller one.- Early
returnand the final expression. Thereturn -1;inside theifneeds 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]withamount = 0gives 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,
minwould 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 <= icheck. The indexi - coinwould go below zero, which ausizecan'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 = 11gives3.coins = [2],amount = 3gives-1.coins = [1, 3, 4],amount = 6gives2.coins = [1],amount = 0gives0.coins = [2],amount = 4gives2.coins = [3, 7],amount = 11gives-1.coins = [186, 419, 83, 408],amount = 6249gives20.
