# LC 322. Coin Change
### [Problem link](https://leetcode.com/problems/coin-change/)
###### tags: `leedcode` `python` `c++` `medium` `DP`
You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> 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 <code>-1</code>.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
```
Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
```
**Example 2:**
```
Input: coins = [2], amount = 3
Output: -1
```
**Example 3:**
```
Input: coins = [1], amount = 0
Output: 0
```
**Constraints:**
- <code>1 <= coins.length <= 12</code>
- <code>1 <= coins[i] <= 2<sup>31</sup> - 1</code>
- <code>0 <= amount <= 10<sup>4</sup></code>
## Solution 1 - DP
#### Python
```python=
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [float("inf")] * (amount + 1)
dp[0] = 0
for coin in coins:
for j in range(coin, amount + 1):
dp[j] = min(dp[j], dp[j - coin] + 1)
return -1 if dp[-1] == float("inf") else dp[-1]
```
#### C++
```cpp=
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int i = 0; i < coins.size(); i++) {
for (int j = coins[i]; j <= amount; j++) {
if (dp[j - coins[i]] != INT_MAX) {
dp[j] = min(dp[j], dp[j - coins[i]] + 1);
}
}
}
return dp.back() == INT_MAX ? -1 : dp.back();
}
};
```
>### Complexity
>n = coins.length
>m = amount
>| | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1 | O(nm) | O(m) |
## Note