Problem Description

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.

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

Problem Link

Coin Change - LeetCode

Reference Video

https://www.youtube.com/watch?v=ZI17bgz07EE&ab_channel=TECHDOSE

Code

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        
        int n = coins.size();
        int dp[n+1][amount+1];
        **sort(coins.begin(),coins.end());**
        for(int i=0;i<=n;i++) {
            for(int j=0;j<=amount;j++) {
                
                if(!i&&!j)
                    dp[i][j] = 0;
                
                else if(i==0&&j)
                    dp[i][j] = INT_MAX;
                
                else if(j==0&&i)
                    dp[i][j] = 0;
                
                else if(j<coins[i-1]||**dp[i][j-coins[i-1]]==INT_MAX**)
                {
                    dp[i][j] = dp[i-1][j];
                    
                    
                }
                
                else
                    dp[i][j] = min(dp[i-1][j],dp[i][j-coins[i-1]]+1);
                    
            }
        }
      
        return dp[n][amount]==INT_MAX ? -1 : dp[n][amount];
    }
};