Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created December 7, 2019 23:59
Show Gist options
  • Save shixiaoyu/d3b596b1b006d4cc03f1b8696e6a64ed to your computer and use it in GitHub Desktop.
Save shixiaoyu/d3b596b1b006d4cc03f1b8696e6a64ed to your computer and use it in GitHub Desktop.
public int coinChangeDP(int[] coins, int amount) {
if (coins == null || coins.length == 0) {
return -1;
}
// lookup contains the min number of coins needed to reach the amount(i.e., index)
int[] lookup = new int[amount + 1];
lookup[0] = 0;
for (int i = 1; i <= amount; i++) {
int min = Integer.MAX_VALUE;
for (int coin : coins) {
if (i >= coin && lookup[i - coin] != -1) {
min = Math.min(min, lookup[i - coin] + 1);
}
}
lookup[i] = (min == Integer.MAX_VALUE ? -1 : min);
}
return lookup[amount];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment