Q21: How do you solve the Coin Change problem using Bottom-Up Dynamic Programming?
Find the fewest coins needed to make up amount. Define dp[i] as the minimum coins needed for amount i. Initialize dp array of size amount + 1 filled with amount + 1 (infinity placeholder), with dp[0] = 0.
Outer loop: i from 1 to amount. Inner loop: each coin in coins. If i - coin >= 0, update dp[i] = Math.min(dp[i], 1 + dp[i - coin]). Return dp[amount] > amount ? -1 : dp[amount].
Bottom-Up Coin Change DP Solution
import java.util.Arrays;
public class CoinChange {
public static int coinChange(int[] coins, int amount) {
int max = amount + 1;
int[] dp = new int[amount + 1];
Arrays.fill(dp, max);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int coin : coins) {
if (i - coin >= 0) {
dp[i] = Math.min(dp[i], 1 + dp[i - coin]);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
}💡 Computes the minimum coin count for target amounts up to amount.
Key Takeaways
- Bottom-Up 1D Dynamic Programming.
- State Relation: $dp[i] = min(dp[i], 1 + dp[i - coin])$.
Knowledge Check
What is the time complexity of the Bottom-Up Coin Change Dynamic Programming solution?