Quantcast
Viewing all articles
Browse latest Browse all 10

•Making change problem using Greedy method

The greedy approach is easy to understand and implement as well.We start with using the largest denomination coin. Once the owed amount is less than the largest, we move to next largest coin, so on.

Denominations are entered in descending order. That is largest one first. Example: 20, 10,5, 1 and amount is 36. And show in below figure.Here 4 coin is Use.We can add a sort method if it’s not, a minor change.

Image may be NSFW.
Clik here to view.

Limitation

Greedy approach works best with Canonical Coin systems and may not produce optimal results in arbitrary coin systems. For example, if denominations are {4, 3, 1}, number 6 is represented as 4×1 3×0 1×2 by this program taking 3 coins. The correct answer in this case is 4×0 3×2 1×0 with just 2 coins.

Code

#include<iostream>
using namespace std;
int main()
{
int deno,coinlist[30],coinuse[30],i;
cout<<"enter number of denominator:"<<endl;
cin>>deno;
cout<<"enter the denomination in descending order:"<<endl;
for(i=0;i<deno;i++)
{
cin>>coinlist[i];
}
int coin;
cout<<"enter the amount:"<<endl;
cin>>coin;
for(i=0;i<deno;i++)
{
coinuse[i]=coin/coinlist[i];
coin%=coinuse[i];
}
cout<<"Solution:"<<endl;
for(i=0;i<deno;i++)
{
cout<<coinlist[i]<<" "<<coinuse[i];
}
}

OUTPUT

Enter number of denominator:4

enter the denomination in descending order:40 33 22 10

Enter the amount:43

Solution:

40×0 33×1 22×0 10×1

Reference

“Introduction to Algorithm” by Thomas H Cormen, Charles E Leiserson, Ronald L Rivest, Clifford Stein.

Thank you

Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 10

Trending Articles