Skip to content

Commit a0ef62f

Browse files
committed
fix: MinCoinCombinationBottomUp and MinCoinCombinationTopDown back to using Integer.MAX_VALUE to fill the dp array for consistent with python solution
1 parent 57f7d50 commit a0ef62f

File tree

2 files changed

+9
-10
lines changed

2 files changed

+9
-10
lines changed

java/Dynamic Programming/MinCoinCombinationBottomUp.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,18 @@ public class MinCoinCombinationBottomUp {
44
public int minCoinCombinationBottomUp(int[] coins, int target) {
55
// The DP array will store the minimum number of coins needed for
66
// each amount. Set each element to a large number initially.
7-
int max = target + 1;
87
int[] dp = new int[target + 1];
9-
Arrays.fill(dp, max);
8+
Arrays.fill(dp, Integer.MAX_VALUE);
109
// Base case: if the target is 0, then 0 coins are needed.
1110
dp[0] = 0;
1211
// Update the DP array for all target amounts greater than 0.
1312
for (int t = 1; t < target + 1; t++) {
1413
for (int coin : coins) {
15-
if (coin <= t) {
14+
if (coin <= t && dp[t - coin]!= Integer.MAX_VALUE) {
1615
dp[t] = Math.min(dp[t], 1 + dp[t - coin]);
1716
}
1817
}
1918
}
20-
return dp[target] != max ? dp[target] : -1;
19+
return dp[target] != Integer.MAX_VALUE ? dp[target] : -1;
2120
}
2221
}

java/Dynamic Programming/MinCoinCombinationTopDown.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,9 @@
22
import java.util.Map;
33

44
public class MinCoinCombinationTopDown {
5-
int max;
6-
75
public int minCoinCombinationTopDown(int[] coins, int target) {
8-
max = target + 1;
96
int res = topDownDp(coins, target, new HashMap<>());
10-
return res == max ? -1 : res;
7+
return res == Integer.MAX_VALUE ? -1 : res;
118
}
129

1310
private int topDownDp(int[] coins, int target, Map<Integer, Integer> memo) {
@@ -20,13 +17,16 @@ private int topDownDp(int[] coins, int target, Map<Integer, Integer> memo) {
2017
return memo.get(target);
2118
}
2219
// Initialize 'minCoins' to a large number.
23-
int minCoins = max;
20+
int minCoins = Integer.MAX_VALUE;
2421
for (int coin : coins) {
2522
// Avoid negative targets.
2623
if (coin <= target) {
2724
// Calculate the minimum number of coins needed if we use
2825
// the current coin.
29-
minCoins = Math.min(minCoins, 1 + topDownDp(coins, target - coin, memo));
26+
int result = topDownDp(coins, target - coin, memo);
27+
if (result!= Integer.MAX_VALUE) {
28+
minCoins = Math.min(minCoins, 1 + result);
29+
}
3030
}
3131
}
3232
memo.put(target, minCoins);

0 commit comments

Comments
 (0)