Conversation
|
Your solution is well-structured and uses dynamic programming correctly. The recurrence relation is appropriate for the unbounded knapsack nature of the problem. However, there are a few areas for improvement:
Here is a revised version of your code with these improvements: class CoinChange {
public int coinChange(int[] coins, int amount) {
if (amount == 0) return 0;
int n = coins.length;
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for (int coin : coins) {
for (int j = coin; j <= amount; j++) {
dp[j] = Math.min(dp[j], 1 + dp[j - coin]);
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
}This version uses a 1D array, initializes with Your current solution is correct and efficient, but with these changes, it becomes more robust and efficient in space. |
No description provided.