# Leetcode 322. Coin Change ###### tags: `Leetcode` https://leetcode.com/problems/coin-change/ ## Description You are given coins of different denominations and a total amount of money amount. Write a function to compute 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. **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 ``` **Example 4:** ``` Input: coins = [1], amount = 1 Output: 1 ``` **Example 5:** ``` Input: coins = [1], amount = 2 Output: 2 ``` **Constraints:** - 1 <= coins.length <= 12 - 1 <= coins[i] <= 231 - 1 - 0 <= amount <= 104 ## Solution in C ### Approach 1 (Brute force) [Time Limit Exceeded] Time Complexity: $O(S^n)$ Space Complexity: $O(1)$ where $S$ is the amount, $n$ is the size of coins. ```c int coinChange(int* coins, int coinsSize, int amount){ if (amount==0) return 0; if (amount<0) return -1; int min_count = -1; for (int i=0; i<coinsSize; i++){ int count = coinChange(coins, coinsSize, amount-coins[i]); if (count!=-1 && (min_count==-1 || count+1 < min_count)) min_count = count+1; } return min_count; } ``` --- ### Approach 2 (Dynamic programming) Time Complexity: $O(S*n)$ Space Complexity: $O(S)$ where $S$ is the amount, $n$ is the size of coins. ```c int coinChange(int* coins, int coinsSize, int amount){ int counts[amount+1]; counts[0]=0; for (int i=1; i<=amount; i++) counts[i]=-1; for (int j=0; j<coinsSize; j++){ if (coins[j]<=amount) counts[coins[j]]=1; } for (int i=1; i<=amount; i++){ for (int j=0; j<coinsSize; j++){ if (counts[i]!=-1 && coins[j]<=amount-i && (counts[i+coins[j]]==-1 || counts[i]+1<counts[i+coins[j]])) counts[i+coins[j]] = counts[i]+1; } } return counts[amount]; } ```