Skip to content

Commit 070bfee

Browse files
committed
Coin change(DP) in C++
1 parent ce3dd92 commit 070bfee

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

Dynamic Programming/Coin_Change.cpp

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
//Link : https://practice.geeksforgeeks.org/problems/coin-change2448/1
2+
3+
//Application of Unbounded Knapsack
4+
// Coin change (1. Total no of ways)
5+
//Note : This problem is similar to count of subset sum but only the difference is that the repetition of same elements are allowed.
6+
7+
// Given a value N, find the number of ways to make change for N cents, if we have infinite supply of each of S = { S1, S2, .. , SM } valued coins.
8+
9+
10+
// Example 1:
11+
12+
// Input:
13+
// n = 4 , m = 3
14+
// S[] = {1,2,3}
15+
// Output: 4
16+
// Explanation: Four Possible ways are:
17+
// {1,1,1,1},{1,1,2},{2,2},{1,3}.
18+
// Example 2:
19+
20+
// Input:
21+
// n = 10 , m = 4
22+
// S[] ={2,5,3,6}
23+
// Output: 5
24+
// Explanation: Five Possible ways are:
25+
// {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5}
26+
// and {5,5}.
27+
28+
// Your Task:
29+
// You don't need to read input or print anything. Your task is to complete the function count() which accepts an array S[] its size m and n as input parameter and returns the number of ways to make change for N cents.
30+
31+
32+
// Expected Time Complexity: O(m*n).
33+
// Expected Auxiliary Space: O(n).
34+
35+
36+
// Constraints:
37+
// 1 <= n,m <= 103
38+
39+
#include<bits/stdc++.h>
40+
using namespace std;
41+
42+
// } Driver Code Ends
43+
class Solution
44+
{
45+
public:
46+
long long int count( int arr[], int m, int n )
47+
{
48+
49+
//code here.
50+
long long int dp[m+1][n+1];
51+
52+
for(int i = 0; i <= m; i++) dp[i][0] = 1;
53+
for(int i = 0; i <= n; i++) dp[0][i] = 0;
54+
55+
for(int i = 1; i <= m; i++){
56+
for(int j = 1; j <= n; j++){
57+
if(arr[i-1] <= j){
58+
dp[i][j] = dp[i][j - arr[i - 1]] + dp[i-1][j];
59+
}else if(arr[i-1] > j){
60+
dp[i][j] = dp[i-1][j];
61+
}
62+
}
63+
}
64+
65+
return dp[m][n];
66+
}
67+
};
68+
69+
// { Driver Code Starts.
70+
int main()
71+
{
72+
int t;
73+
cin>>t;
74+
while(t--)
75+
{
76+
int n,m;
77+
cin>>n>>m;
78+
int arr[m];
79+
for(int i=0;i<m;i++)
80+
cin>>arr[i];
81+
Solution ob;
82+
cout<<ob.count(arr,m,n)<<endl;
83+
}
84+
85+
86+
return 0;
87+
} // } Driver Code Ends

0 commit comments

Comments
 (0)