I was looking for a good solution to the Change-making problem and I found this code(Python):
target = 200
coins = [1,2,5,10,20,50,100,200]
ways = [1]+[0]*target
for coin in coins:
for i in range(coin,target+1):
ways[i]+=ways[i-coin]
print(ways[target])
I have no problems understanding what the code literally does,but I can't understand WHY it works. Anyone can help?
The change making problem is an optimization problem that asks "What is the minimum number of coins I need to make up a specific total?" The input to the Change Making Problem is a sequence of positive integers [d1, d2, d3 ... dn] and T , where di represents a coin denomination and T is the target amount.
Greedy method A coin system is called "canonical" if the greedy algorithm always solves its change-making problem optimally.
Problem Statement We are given an array of coins having different denominations and an integer sum representing the total money, you have to return the fewest coins that you will need to make up that sum if it's not possible to construct that sum then return -1. Explanation: There is no combination present with sum 15.
To get all possible sets that elements are equal to 'a' or 'b' or 'c' (our coins) that sum up to 'X' you can:
So number of ways you can get X is sum of numbers of ways you can get X-a and X-b and X-c.
ways[i]+=ways[i-coin]
Rest is simple recurrence.
Extra hint: at the start you can get set with sum zero in exactly one way (empty set)
ways = [1]+[0]*target
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With