Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding change-making algorithm

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?

like image 931
gyosko Avatar asked Feb 21 '13 00:02

gyosko


People also ask

What do you mean by making change problem in algorithm?

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.

Which of following algorithmic approach is best suitable for change making problem?

Greedy method A coin system is called "canonical" if the greedy algorithm always solves its change-making problem optimally.

Is coin change possible problem?

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.


1 Answers

To get all possible sets that elements are equal to 'a' or 'b' or 'c' (our coins) that sum up to 'X' you can:

  • Take all such sets that sum up to X-a and add an extra 'a' to each one.
  • Take all such sets that sum up to X-b and add an extra 'b' to each one.
  • Take all such sets that sum up to X-c and add an extra 'c' to each one.

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
like image 163
fsw Avatar answered Sep 20 '22 07:09

fsw