322. Coin Change
Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1Input: coins = [2], amount = 3
Output: -1Input: coins = [1], amount = 0
Output: 0Last updated
Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1Input: coins = [2], amount = 3
Output: -1Input: coins = [1], amount = 0
Output: 0Last updated
class Solution {
public int coinChange(int[] coins, int amount) {
if (amount == 0) return 0;
int[] dp = new int[amount + 1];
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
dp[i] = Integer.MAX_VALUE;
for (int c : coins) {
if (i >= c && dp[i - c] != Integer.MAX_VALUE) {
dp[i] = Math.min(dp[i], dp[i - c] + 1);
}
}
}
if (dp[amount] < Integer.MAX_VALUE) return dp[amount];
else return -1;
}
}