#322
Medium Algorithms Coin change
Array Dynamic Programming Breadth-First Search
48.0% acceptance
Jan 12, 2026
20833
540
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn coin_change(coins: Vec<i32>, amount: i32) -> i32 {
let amount = amount as usize;
let mut dp = vec![amount + 1; amount + 1];
dp[0] = 0;
for i in 1..=amount {
for &coin in &coins {
let coin = coin as usize;
if coin <= i {
dp[i] = dp[i].min(dp[i - coin] + 1);
}
}
}
if dp[amount] > amount {
-1
} else {
dp[amount] as i32
}
}
}