Skip to content

Commit 31ab800

Browse files
committed
Coin Change Problem Code Snippets
1 parent 08cd532 commit 31ab800

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.java.coin.change;
2+
3+
import java.util.Arrays;
4+
public class MaxNoOfWays {
5+
6+
public static void main(String[] args) {
7+
int n = 5;
8+
int coins[] = {1,2,5};
9+
int noOfCoins = coins.length;
10+
11+
int table[] = new int[n+1];
12+
table[0] = 1;
13+
for(int i=0;i<noOfCoins;i++){
14+
for(int j=coins[i];j<=n;j++)
15+
table[j] += table[j-coins[i]];
16+
// System.out.println(i+" "+Arrays.toString(array));
17+
}
18+
System.out.println(table[n]);
19+
System.out.println("Maximum no of ways to get change is :: "+table[n]);
20+
}
21+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.java.coin.change;
2+
3+
import java.util.Arrays;
4+
import java.util.Scanner;
5+
6+
public class MinimumCoins {
7+
public static void main(String[] args) {
8+
Scanner scanner = new Scanner(System.in);
9+
int noOfCoins = Integer.parseInt(scanner.nextLine().trim());
10+
int coins[] = new int[noOfCoins];
11+
for(int i=0;i<noOfCoins;i++)
12+
coins[i] = Integer.parseInt(scanner.nextLine().trim());
13+
int n = Integer.parseInt(scanner.nextLine().trim());
14+
15+
int table[] = new int[n+1];
16+
table[0] = 0;
17+
18+
for(int i=1;i<=n;i++)
19+
table[i] = Integer.MAX_VALUE;
20+
21+
for(int i=1;i<=n;i++){
22+
for(int j=0;j<noOfCoins;j++)
23+
if(coins[j] <= i){
24+
int sub_res = table[i-coins[j]];
25+
if(sub_res != Integer.MAX_VALUE && sub_res+1 < table[i])
26+
table[i] = sub_res+1;
27+
}
28+
// System.out.println(i+" "+Arrays.toString(table));
29+
}
30+
System.out.print(table[n]);
31+
scanner.close();
32+
}
33+
}
34+
/*
35+
36+
Input
37+
4
38+
7
39+
3
40+
2
41+
6
42+
13
43+
Output
44+
2
45+
46+
Input
47+
3
48+
1
49+
2
50+
10
51+
5
52+
53+
*/

0 commit comments

Comments
 (0)