-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamicCoin.c
41 lines (33 loc) · 1.16 KB
/
DynamicCoin.c
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
//QUESTION: Coin change problem.
//CODE:
#include <stdio.h>
// Function to find the number of ways to get the desired amount
int coinChange(int coins[], int n, int amount) {
// Create a table to store results of subproblems
int dp[amount + 1];
// Initialize all values to 0
for (int i = 0; i <= amount; i++) {
dp[i] = 0;
}
// Base case: there is one way to make the amount 0
dp[0] = 1;
// Iterate over all coin denominations
for (int i = 0; i < n; i++) {
// Update dp[] values for all amounts greater than or equal to the current coin's value
for (int j = coins[i]; j <= amount; j++) {
dp[j] += dp[j - coins[i]];
}
}
// The answer is in dp[amount]
return dp[amount];
}
int main() {
// Example coin denominations
int coins[] = {1, 2, 5}; // Available coin denominations
int n = sizeof(coins) / sizeof(coins[0]); // Number of coin types
int amount = 11; // Total amount
// Call the function and display the result
int result = coinChange(coins, n, amount);
printf("Number of ways to make change for %d is: %d\n", amount, result);
return 0;
}