Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic programming - Coin change decision

I'm reviewing some old notes from my algorithms course and the dynamic programming problems are seeming a bit tricky to me. I have a problem where we have an unlimited supply of coins, with some denominations x1, x2, ... xn and we want to make change for some value X. We are trying to design a dynamic program to decide whether change for X can be made or not (not minimizing the number of coins, or returning which coins, just true or false).

I've done some thinking about this problem, and I can see a recursive method of doing this where it's something like...

MakeChange(X, x[1..n this is the coins])
    for (int i = 1; i < n; i++)
    {
        if ( (X - x[i] ==0) || MakeChange(X - x[i]) )
            return true;
    }
    return false;

Converting this a dynamic program is not coming so easily to me. How might I approach this?

like image 998
Tony Avatar asked Apr 13 '10 23:04

Tony


People also ask

What is making change problem dynamic programming?

Making Change problem is to find change for a given amount using a minimum number of coins from a set of denominations. Explanation : If we are given a set of denominations D = {d0, d1, d2, …, dn} and if we want to change for some amount N, many combinations are possible.

What is meant by coin changing problem?

The change-making problem addresses the question of finding the minimum number of coins (of certain denominations) that add up to a given amount of money. It is a special case of the integer knapsack problem, and has applications wider than just currency.

Is coin change a knapsack problem?

The coin-change problem resembles the 0-1 Knapsack Problem in Dynamic Programming. It has two versions: Finding the minimum number of coins, of certain denominations, required to make a given sum. Finding the total number of possible ways a given sum can be made from a given set of coins.


1 Answers

Your code is a good start. The usual way to convert a recursive solution to a dynamic-programming one is to do it "bottom-up" instead of "top-down". That is, if your recursive solution calculates something for a particular X using values for smaller x, then instead calculate the same thing starting at smaller x, and put it in a table.

In your case, change your MakeChange recursive function into a canMakeChange table.

canMakeChange[0] = True
for X = 1 to (your max value):
   canMakeChange[X] = False
   for i=1 to n:
     if X>=x[i] and canMakeChange[X-x[i]]==True: 
       canMakeChange[X]=True
like image 91
ShreevatsaR Avatar answered Oct 31 '22 16:10

ShreevatsaR