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.


Test Cases

Input:

(int[]) coins = [1,2,5]
(int) amount = 11

Output:

(int) 3

Explanation:

11 = 5 + 5 + 1

Input:

(int[]) coins = [2]
(int) amount = 3

Output:

(int) -1

Input:

(int[]) coins = [1]
(int) amount = 0

Output:

(int) 0

Solution

int min(int num1, int num2) {
    return (num1 < num2 ) ? num1 : num2;
}

int coinChange(int* coins, int coinsSize, int amount){
    int max = amount + 1;
    int dp[amount+1];
    dp[0] = 0;
    for (int i = 1; i <= amount; i++) {
        dp[i] = max;
        for(int j=0; j<coinsSize; j++) {
            int coin = coins[j];
            if (coin <= i) {
                dp[i] = min(dp[i], dp[i - coin] + 1);
            }
        }
    }
    return dp[amount] > amount ? -1 : dp[amount];
}
class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        int max = amount + 1;
        vector<int> dp(amount+1, max);
        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            for(int j=0; j<coins.size(); j++) {
                int coin = coins[j];
                if (coin <= i) {
                    dp[i] = min(dp[i], dp[i - coin] + 1);
                }
            }
        }
        return dp[amount] > amount ? -1 : dp[amount];
    }
};
class Solution {
    public int coinChange(int[] coins, int amount) {
        int max = amount + 1;
        int[] dp = new int[amount+1];
        Arrays.fill(dp, max);
        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            for(int coin: coins) {
                if (coin <= i) {
                    dp[i] = Math.min(dp[i], dp[i - coin] + 1);
                }
            }
        }
        return dp[amount] > amount ? -1 : dp[amount];
    }
}
class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        mx = amount + 1
        dp = [mx]*mx
        dp[0] = 0
        for i in range(1, amount+1):
            for coin in coins:
                if coin <= i:
                    dp[i] = min(dp[i], 1 + dp[i - coin])
        return -1 if dp[amount] > amount else dp[amount]
Time Complexity: O(n*amount)
Space Complexity: O(amount)