Skip to content

Commit b913528

Browse files
committed
add: MinCoinCombinationBottomUp
1 parent e9a9366 commit b913528

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import java.util.Arrays;
2+
3+
public class MinCoinCombinationBottomUp {
4+
public int minCoinCombinationBottomUp(int[] coins, int target) {
5+
// The DP array will store the minimum number of coins needed for
6+
// each amount. Set each element to a large number initially.
7+
int max = target + 1;
8+
int[] dp = new int[target + 1];
9+
Arrays.fill(dp, max);
10+
// Base case: if the target is 0, then 0 coins are needed.
11+
dp[0] = 0;
12+
// Update the DP array for all target amounts greater than 0.
13+
for (int t = 1; t < target + 1; t++) {
14+
for (int coin : coins) {
15+
if (coin <= t) {
16+
dp[t] = Math.min(dp[t], 1 + dp[t - coin]);
17+
}
18+
}
19+
}
20+
return dp[target] != max ? dp[target] : -1;
21+
}
22+
}

0 commit comments

Comments
 (0)