-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCOIN_CHANGE.cpp
106 lines (79 loc) · 2.21 KB
/
COIN_CHANGE.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#define inf -1
using namespace std;
void printUsedCoins(int* coin_parent , int amount);
bool isGreaterThan(int a , int b);
int* create_n_array(int value);
int change(int *coins, int s , int value);
int main()
{
int *coinArr, no_of_coins , value, n=0;
cout<< "Input number of denominations "<<endl;
cin>> no_of_coins ;
coinArr = new int[no_of_coins];
while(n!=no_of_coins)
{
cout<< "Input coins "<<endl;
cin>> coinArr[n] ;
n++;
}
cout<< "Input the amount "<<endl;
cin>> value ;
cout<<endl << "Number of coins required " << change(coinArr,no_of_coins,value);
return 0;
}
bool isGreaterThan(int a , int b)
{
bool result = false ;
if(a!=-1 && b!=-1)
{
result = a>b ;
}
else if( a==-1 )
{
if(b!=-1) result=true;
}
return result;
}
int* create_n_array(int value)
{
int *a = new int[value+1];
a[0] =0;
for(int i=1; i<=value ; i++ )
{
a[i]=inf;
}
return a;
}
int change(int *coins, int s , int value)
{
int *Current_value = create_n_array(value);
int *Parent_Coins_Used = create_n_array(value);
int coinUsed ;
for(int v =1 ; v<=value ; v++)
{
coinUsed = inf;
for(int i =0 ; i <s ; i++)
{
if( coins[i]<=v )
{
/* Current_value[v] > Current_value[ v - coins[i] ] + 1) */
if(isGreaterThan( Current_value[v] , Current_value[ v - coins[i] ] + 1))
{
Current_value[ v ] = Current_value[ v - coins[i] ] + 1 ;
coinUsed=i ;
}
}
}
Parent_Coins_Used[ v ] = coins[coinUsed]; // storing index of the used coin
}
cout<< endl << "The coins used are " <<endl;
printUsedCoins(Parent_Coins_Used , value);
return Current_value[value];
}
void printUsedCoins(int* coin_parent , int amount)
{
if(amount==0) return ;
printUsedCoins(coin_parent, amount-coin_parent[amount]);
cout<< " " <<coin_parent[amount] << " ";
}