forked from RasPat1/practice-codewars
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CoinFree.java
51 lines (39 loc) · 1.11 KB
/
CoinFree.java
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
import java.util.*;
public class CoinFree {
static Map<Integer, Integer> memo = new HashMap<>();
public static int solve(int amount, int[] denom) {
int[] denomSorted = new int[denom.length];
Arrays.sort(denom);
for (int i = 0; i < denom.length; i++) {
denomSorted[i] = denom[denom.length - 1 - i];
}
return solve(amount, denomSorted, 1);
}
public static int solve(int amount, int[] denom, int count) {
int minCoins = Integer.MAX_VALUE;
if (memo.containsKey(amount)) {
return memo.get(amount);
}
if (amount <= 0) {
return 0;
}
for (int coin: denom) {
if (amount == 12010000) {
System.out.println(coin);
}
int min = minCoins;
if (amount == coin) {
return count;
} else if (amount > coin) {
return solve(amount - coin, denom, count + 1);
} else {
min = Integer.MAX_VALUE;
}
if (min < minCoins) {
minCoins = min;
}
}
memo.put(amount, minCoins);
return minCoins;
}
}