Skip to content

Commit 6ef27f1

Browse files
authored
Update Coin Change.java
1 parent 91b7257 commit 6ef27f1

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

Medium/Coin Change.java

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,28 @@
11
class Solution {
22
public int coinChange(int[] coins, int amount) {
3-
if (amount < 1) {
4-
return 0;
5-
}
6-
return coinChange(coins, amount, new int[amount]);
3+
Integer[] memo = new Integer[amount + 1];
4+
return coinChangeMemoization(coins, amount, memo);
75
}
8-
9-
private int coinChange(int[] coins, int amount, int[] memo) {
6+
7+
private int coinChangeMemoization(int[] coins, int amount, Integer[] memo) {
108
if (amount < 0) {
119
return -1;
1210
}
1311
if (amount == 0) {
1412
return 0;
1513
}
16-
if (memo[amount - 1] != 0) {
17-
return memo[amount - 1];
14+
if (memo[amount] != null) {
15+
return memo[amount];
1816
}
19-
int min = Integer.MAX_VALUE;
17+
int minCount = Integer.MAX_VALUE;
2018
for (int coin : coins) {
21-
int res = coinChange(coins, amount - coin, memo);
22-
if (res >= 0 && res < min) {
23-
min = 1 + res;
19+
int count = coinChangeMemoization(coins, amount - coin, memo);
20+
if (count == -1) {
21+
continue;
2422
}
23+
minCount = Math.min(minCount, count + 1);
2524
}
26-
memo[amount - 1] = min == Integer.MAX_VALUE ? -1 : min;
27-
return memo[amount - 1];
25+
memo[amount] = minCount == Integer.MAX_VALUE ? -1 : minCount;
26+
return memo[amount];
2827
}
2928
}

0 commit comments

Comments
 (0)