-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSolution.java
More file actions
83 lines (60 loc) · 1.76 KB
/
Solution.java
File metadata and controls
83 lines (60 loc) · 1.76 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package hackrank.algorithm.dynamic.coin;
import java.io.InputStream;
import java.util.Scanner;
/**
* Coin Change Challenge
*
* @see https://www.hackerrank.com/challenges/coin-change
*/
public class Solution {
public static void main(String[] args) {
CoinChanger changer = readInput(System.in);
System.out.println(changer.countWays());
}
public static CoinChanger readInput(InputStream stream) {
Scanner scanner = new Scanner(stream);
int amount = scanner.nextInt();
int size = scanner.nextInt();
int[] coins = new int[size];
for (int i = 0; i < size; i++) {
coins[i] = scanner.nextInt();
}
scanner.close();
return new CoinChanger(amount, coins);
}
}
class CoinChanger {
private int amount;
private int[] coins;
CoinChanger(int amount, int[] coins) {
this.amount = amount;
this.coins = coins;
}
public long countWays() {
long[] ways = new long[amount + 1];
ways[0] = 1;
for (int i = 0; i < coins.length; i++) {
int coin = coins[i];
for (int j = coin; j <= amount; j++) {
ways[j] += ways[j - coin];
}
}
return ways[amount];
}
public long countWaysRecursive() {
return countRecursive(coins.length, amount);
}
private long countRecursive(int available, int value) {
if (value == 0) {
return 1;
}
if (value < 0) {
return 0;
}
if (available <= 0 && value >= 1) {
return 0;
}
int reducedValue = value - coins[available - 1];
return countRecursive(available - 1, value) + countRecursive(available, reducedValue);
}
}