Suppose we have coins of different denominations and a total amount of money amount. We have to define one function to compute the fewest number of coins that we need to make up that amount. When that amount of money cannot be accommodated by any combination of the coins, return -1. So if the input is [1,2,5], and the amount is 64, the output is 14. This is formed using 12*5 + 2 + 2 = 64.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution(object): def coinChange(self, coins, amount): if amount == 0 : return 0 if min(coins) > amount: return -1 dp = [-1 for i in range(0, amount + 1)] for i in coins: if i > len(dp) - 1: continue dp[i] = 1 for j in range(i + 1, amount + 1): if dp[j - i] == -1: continue elif dp[j] == -1: dp[j] = dp[j - i] + 1 else: dp[j] = min(dp[j], dp[j - i] + 1) return dp[amount] ob1 = Solution() print(ob1.coinChange([1,2,5],64))