You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1
Input: coins = [1,5,10,25], amount = 30
Output: 2
Explanation: 25 + 5 = 30
Example 2
Input: coins = [2], amount = 3
Output: -1
Explanation: Cannot make 3 from coin 2.
1 <= coins.length <= 121 <= coins[i] <= 2^31 - 10 <= amount <= 10^4Build dp[0..amount] where dp[i] = min coins to make amount i. dp[i] = min(dp[i - coin] + 1) for each coin.
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1); // infinity
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int coin : coins) {
if (coin <= i) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}Time: O(amount * coins.length) · Space: O(amount)