You are given coins of different denominations and a total amount of money amount. Write a function to compute 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:
coins = [1, 2, 5]
, amount = 11
return 3
(11 = 5 + 5 + 1)
Example 2:
coins = [2]
, amount = 3
return -1
.
1 public class Solution { 2 public int coinChange(int[] coins, int amount) { 3 if (coins == null || coins.length == 0 || amount < 0) return -1; 4 5 int[] count = new int[amount + 1]; 6 for (int i = 1; i < count.length; i++) { 7 count[i] = Integer.MAX_VALUE; 8 } 9 10 for (int i = 1; i <= amount; i++) { 11 for (int j = coins.length - 1; j >= 0; j--) { 12 if (i - coins[j] >= 0 && count[i - coins[j]] != Integer.MAX_VALUE) { 13 if (count[i - coins[j]] + 1 < count[i]) { 14 count[i] = count[i - coins[j]] + 1; 15 } 16 } 17 } 18 } 19 return count[amount] == Integer.MAX_VALUE ? -1 : count[amount]; 20 } 21 }