Skip to content

Commit 88c04a1

Browse files
authored
Merge pull request TheAlgorithms#302 from varunu28/master
Create CoinChange.java
2 parents eed6f33 + 7208bdd commit 88c04a1

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Dynamic Programming/CoinChange.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
*
3+
* @author Varun Upadhyay (https://github.com/varunu28)
4+
*
5+
*/
6+
7+
public class CoinChange {
8+
9+
// Driver Program
10+
public static void main(String[] args) {
11+
12+
int amount = 12;
13+
int[] coins = {1, 2, 5};
14+
15+
System.out.println("Number of combinations of getting change for " + amount + " is: " + change(coins, amount));
16+
}
17+
18+
/**
19+
* This method finds the number of combinations of getting change for a given amount and change coins
20+
*
21+
* @param coins The list of coins
22+
* @param amount The amount for which we need to find the change
23+
* Finds the number of combinations of change
24+
**/
25+
public static int change(int[] coins, int amount) {
26+
27+
int[] combinations = new int[amount+1];
28+
combinations[0] = 1;
29+
30+
for (int coin : coins) {
31+
for (int i=coin; i<amount+1; i++) {
32+
if (i>=coin) {
33+
combinations[i] += combinations[i-coin];
34+
}
35+
}
36+
// Uncomment the below line to see the state of combinations for each coin
37+
// printAmount(combinations);
38+
}
39+
40+
return combinations[amount];
41+
}
42+
43+
// A basic print method which prints all the contents of the array
44+
public static void printAmount(int[] arr) {
45+
46+
for (int i=0; i<arr.length; i++) {
47+
System.out.print(arr[i] + " ");
48+
}
49+
System.out.println();
50+
}
51+
52+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy