Skip to content

Commit a63524f

Browse files
Merge pull request matthewsamuel95#33 from shalithasuranga/newalgo
Coin change problem
2 parents 0072ac3 + 6f86730 commit a63524f

File tree

2 files changed

+70
-1
lines changed

2 files changed

+70
-1
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
/*
5+
6+
Algorithm : Coin Change Problem (Minimum Coins)
7+
Type : DP
8+
9+
Problem
10+
11+
Given a value V, if we want to make change for V cents, and we have infinite supply of each of C = { C1, C2, .. , Cm} valued coins, what is the minimum number of coins to make the change?
12+
13+
Example
14+
15+
Input
16+
17+
4 4
18+
1 2 3 5
19+
20+
Output
21+
22+
2
23+
24+
Explanation
25+
26+
We can make 4 using {2,2} or {1,3}
27+
28+
*/
29+
30+
// m is size of coins array (number of different coins)
31+
int minCoins(vector<int> coins, int m, int V)
32+
{
33+
// table[i] will be storing the minimum number of coins
34+
// required for i value. So table[V] will have result
35+
int table[V+1];
36+
37+
// Base case (If given value V is 0)
38+
table[0] = 0;
39+
40+
// Initialize all table values as Infinite
41+
for (int i=1; i<=V; i++)
42+
table[i] = INT_MAX;
43+
44+
// Compute minimum coins required for all
45+
// values from 1 to V
46+
for (int i=1; i<=V; i++)
47+
{
48+
// Go through all coins smaller than i
49+
for (int j=0; j<m; j++)
50+
if (coins[j] <= i)
51+
{
52+
int sub_res = table[i-coins[j]];
53+
if (sub_res != INT_MAX && sub_res + 1 < table[i])
54+
table[i] = sub_res + 1;
55+
}
56+
}
57+
return table[V];
58+
}
59+
60+
61+
int main()
62+
{
63+
int m,V;
64+
cin >> m >> V;
65+
vector <int> coins(m);
66+
for (int i = 0; i < m; i++) cin >> coins[i];
67+
cout << minCoins(coins, m, V);
68+
return 0;
69+
}

DP/Coin Change Problem/CoinChangeProblem.cpp renamed to DP/Coin Change Problem/NoOfWays.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ using namespace std;
77

88
/*
99
10-
Algorithm : Coin Change Problem
10+
Algorithm : Coin Change Problem (No of Ways)
1111
Type : DP
1212
1313
Problem

0 commit comments

Comments
 (0)