LeetCode 322 - Coin Change
Table of Contents
Problem Statement
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.
Using Dynamic Programming
We can use Dynamic Programming (DP) to calculate the minimum number of coins needed to form the given amount or return -1
if itβs not possible.
Initialization:
dp[i] = amount + 1
is used as a sentinel value to represent an initially impossible number of coins. This value ensures that comparisons withmin()
always work correctly.
Dynamic Programming Transition:
- For each coin, iterate through the possible amounts starting from
coin
to amount. If a solution exists fordp[i - coin]
, updatedp[i]
by considering the new coin.
- For each coin, iterate through the possible amounts starting from
Result:
- If
dp[amount]
has been updated to a valid value, return it. Otherwise, return-1
.
- If
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for (int coin : coins) {
for (int i = coin; i <= amount; i++) {
dp[i] = min(dp[i], dp[i - coin] + 1);
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
};
Complexity
Time Complexity: π(π β π)
- Where π is the number of coins and π is the amount. Each coin is used to update the
dp
array for all amounts up toamount
.
Space Complexity: π(π)
- Where π is the amount. The
dp
array has a size of ππππ’ππ‘ + 1.
Conclusion
This implementation is efficient and handles edge cases like when amount = 0
or coins
contains duplicates.
This is a classic example of the Unbounded Knapsack Problem where each coin can be used an unlimited number of times.