-5

Suppose I have 4 coins of denominations 1 3 4 5. I want to make it 7. I learn how to find how many possible ways that can be done. But I want to determine what is the minimum number of coins that must be used to do that. Example: 5+1+1=7 again 3+4=7. So the minimum number of coins is 2. Any pseudo code or explanation or source code will be helpful

Akash
  • 1
  • 2
  • 6
    the site dosen't works like this^. you need to tell us what have you done/written/researched , and if you get stuck at some point , SO helps. – Abhinav Gauniyal Apr 10 '15 at 16:44
  • 1
    @AbhinavGauniyal Wrong. SO isn't supposed to be a free homework assignments solver. But in fact, for some strange reason, it works like this all the time. ;( See answers below. – Ivan Aksamentov - Drop Apr 10 '15 at 17:07
  • 1
    Questions asking for help need to include what you have tried and what results you are getting, or they will be closed as off-topic. – ssube Apr 10 '15 at 17:31

2 Answers2

0

If you want to make change for the number n, set up an array number_of_coins[n] and fill it in from left to right. number_of_coins[0] is 0, obviously. The next few you can do by hand (although once you have an algorithm it will fill them in automatically). To fill in larger entries m in the array, think about this: what if I removed 1 cent from m? Or 3 cents? Or 4 cents? Or 5 cents?

Once you have the number of coins array up to n, you can walk backwards through it to find the exact coins to use.

Edward Doolittle
  • 4,002
  • 2
  • 14
  • 27
0

I'll take a stab at it. I'm think you should define a vector of your denominations:

vector<int> denominations {1,3,5,7};

from there, write a recursive function that takes in the denominations, as well as the amount to make from the denominations:

int recursive_totals(const vector<int> denominations, int amount_to_make);

this function would return 0 if the amount_to_make is less than or equal to 0, otherwise it would loop through the denominations:

int sum_totals = 0;
for (int denom : denominations)
{
    if (amount_to_make - denom == 0)
        sum_totals+=1;
    else
        sum_totals+=recursive_totals(denominations, amount_to_make - denom);
}

this is rough code and may need adjusting but I think a recursive function works here. An immediate problem I see is that order won't matter the way I wrote it here, and you could get duplicates, but there is a way to work around that.

EDIT: I got it working, but won't post the code here. This method works, and if you choose to try it, feel free to ask any questions you need and I will try to help.

dwcanillas
  • 3,562
  • 2
  • 24
  • 33