Created
December 7, 2019 23:59
-
-
Save shixiaoyu/d3b596b1b006d4cc03f1b8696e6a64ed to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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