Coin Change II
Let's solve the Coin Change II problem using Dynamic Programming.
Statement
Suppose you are given a list of coins and a certain amount of money. Each coin in the list is unique and of a different 0
.
Note: You may assume that for each combination you make, you have an infinite number of each coin. In simpler terms, you can use a specific coin as many times as you want.
Let's say you have only two coins,
3 coins of
cents: . 1 coin of
cents and 1 coin of cents:
Constraints:
1 <=
coins.length
<= 3001 <=
coins[i]
<= 5000All the coins have a unique value.
0 <=
amount
<= 5000
Examples
Let's see a few more examples to get a better understanding of the problem statement:
No. | Coins | Amount | Number of ways |
1 | [1, 2, 5] | 7 | 6 |
2 | [1, 5, 10, 25] | 10 | 4 |
3 | [7] | 9 | 0 |
4 | [9,10,11] | 0 | 1 |
Try it yourself
Implement your solution in the following playground.
def count_ways(coins, amount):# replace this placeholder return statement with your codereturn -1
Note: If you clicked the “Submit” button and the code timed out, this means that your solution needs to be optimized in terms of running time.
Hint: Use dynamic programming and see the magic.
Solution
We will first explore the naive recursive solution to this problem and then see how it can be improved using the Unbounded Knapsack dynamic programming pattern.
Naive approach
A naive approach to solve this problem would be to make all the possible combinations of coins or generate all subsets of coin denominations that sum up to the required amount.
While making the combinations, a point to keep in mind is that we should try to avoid repeatedly counting the same combinations. For example,
As a base case, we return
The slides below will help you visualize the process.
Now, let's look at the code in the code widget below for the solution we just discussed.
def count_ways_rec(coins, amount, maximum):if amount == 0: # base case 1return 1if amount < 0: # base case 2return 0ways = 0# iterate over coinsfor coin in coins:# to avoid repetition of similar sequences, use coins smaller than maximumif coin <= maximum and amount - coin >= 0:# notice how maximum is set to the current value of coin in recursive callways += count_ways_rec(coins, amount-coin, coin)return waysdef count_ways(coins, amount):return count_ways_rec(coins, amount, max(coins))def main():coins_lists = [[7], [1, 2, 5], [10], [49, 233, 96, 132, 188],[310, 278, 99, 326, 5, 575, 569, 15, 141, 54],[2823, 4551, 1750, 49, 3256, 405, 380, 4785, 3893, 874],[17, 1422, 30, 1153, 1275], [1460], [9, 10, 11]]amounts = [9, 5, 10, 225, 350, 3200, 700, 2000, 0]# You can uncomment the lines below and check how this recursive solution causes a time-out# Length of coins_list used here is 45# coins_lists.append([4021, 2158, 3577, 2157, 3928, 1229, 3888,# 1464, 56, 4945, 138, 3148, 699, 3001, 83,# 170, 4673, 941, 1539, 4904, 4118, 1953, 17,# 2963, 4406, 2359, 2363, 2288, 4147, 1070,# 4006, 3824, 467, 1785, 3365, 264, 3598,# 1132, 3093, 3634, 3122, 3618, 4545, 3256, 836])# amounts.append(5000)for i in range(len(amounts)):print(i+1, ".", "\tCoins: ", coins_lists[i], sep="")print("\tAmount: ", amounts[i], sep="")num_ways = count_ways(coins_lists[i], amounts[i])print("\tNumber of Ways: ", num_ways, sep="")print("-" * 100)print()if __name__ == '__main__':main()
Note: Please observe that if you include the test case commented out in the driver code, the solution is likely to time out. Try to solve the larger problem using the dynamic programming solutions provided below and see the difference.
Time complexity
If the length of the list coins
is