-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoinChangingDP.cpp
More file actions
92 lines (80 loc) · 1.72 KB
/
Copy pathCoinChangingDP.cpp
File metadata and controls
92 lines (80 loc) · 1.72 KB
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
#include<iostream>
using namespace std;
int min(int a, int b){
if(a>b)
return b;
else
return a;
}
int main(){
int n;
int amount;
int count = 0;
cout<<"Enter Number of Coin Denominations: ";
cin>>n;
int coin[n];
for(int i = 0; i < n; i++){
cin>>coin[i];
}
cout<<"\nEnter Amount: ";
cin>>amount;
int V[n][amount+1];
for (int i = 0; i < n; i++)
{
V[i][0] = 0;
}
for (int i = 0; i < n; i++)
{
for (int j = 1; j <= amount; j++)
{
if (coin[i]-j>0)
{
if(i==0){
V[i][j] = 0;
continue;
}
V[i][j] = V[i-1][j];
}
else{
if(i==0){
V[i][j] = 1 + V[i][j-coin[i]];
continue;
}
V[i][j] = min(V[i-1][j], 1 + V[i][j-coin[i]]);
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= amount; j++)
{
cout<<V[i][j]<<"\t";
}
cout<<"\n";
}
int i = n-1;
int j = amount;
cout<<"\nNo of Coins Required are "<<V[i][j];
cout<<"\n";
int noofcoins = V[i][j];
while(amount>0 && noofcoins!=0){
while(V[i][j]==V[i-1][j] && i>0){
i--;
}
while(V[i][j]==V[i][j-1]){
j--;
}
amount = amount - coin[i];
cout<<coin[i]<<" ";
noofcoins--;
int temp = j;
while(j>0){
if(V[i][temp]==noofcoins){
j = temp;
}
temp--;
}
i--;
}
return 0;
}