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.

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

Note:
You may assume that you have an infinite number of each kind of coin.

Solution : Dynamic Programming

Top Down Approach : Recursion + Memoization

class Solution {
    public int coinChange(int[] coins, int amount) {

        //Base case
        if(amount == 0)
            return 0;
        
        int[] dp = new int[amount+1];
        
        int res = minCoins(amount,coins,coins.length,dp);
        
        return res == Integer.MAX_VALUE ? -1 : res;
    }
    
    public int minCoins(int n,int[] coins,int T,int[] dp)
    {
        //Base case
        if(n == 0)
            return 0;
        
        //Lookup
        if(dp[n] != 0)
            return dp[n];
        
        //Recursive Case
        int ans = Integer.MAX_VALUE;
        
        for(int i=0;i<T;i++)
        {
            if(n-coins[i] >= 0)
            {
                int subProblem = minCoins(n-coins[i],coins,T,dp);
                
                if(subProblem != Integer.MAX_VALUE)
                    ans = Math.min(ans,subProblem + 1);
            }  
        }
        dp[n] = ans;
        return dp[n];
    }
}

Time Complexity: O(T * N)

Space Complexity: O(N)

Bottom Up Approach

class Solution {
    public int coinChange(int[] coins, int amount) {
        if(amount == 0)
            return 0;
        int res = findMinCoinsBU(amount,coins,coins.length);
        
        return res == Integer.MAX_VALUE ? -1 : res;
     
    }
    
    public int findMinCoinsBU(int N,int[] coins,int T)
    {
        int[] dp = new int[N+1];
        
        for(int n=1;n<=N;n++)
        {
            dp[n] = Integer.MAX_VALUE;
            
            for(int i=0;i<T;i++)
            {
                if(n - coins[i] >= 0)
                {
                    int subProblem = dp[n-coins[i]];
                    if(subProblem != Integer.MAX_VALUE)
                    dp[n] = Math.min(subProblem+1, dp[n]);
                    
                }
            }
        }
        return dp[N];
    }
    
}

Time Complexity: O(T * N)

Space Complexity: O(N)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s