-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathCoinChange.java
More file actions
32 lines (27 loc) · 876 Bytes
/
CoinChange.java
File metadata and controls
32 lines (27 loc) · 876 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* LeetCode 322 https://leetcode.com/problems/coin-change/
*/
class Solution {
public int coinChange(int[] coins, int amount) {
if (coins.length == 0 || amount < 0) {
return -1;
}
// for x amount, int[x] is the fewest coin number to get that x amount
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount+1);
// base case
dp[0] = 0;
// checking against all status
for (var i = 0; i < amount + 1; i++) {
// checking against all choices
for (int coin : coins) {
// invalid
if ( i - coin < 0) {
continue;
}
dp[i] = Math.min(dp[i-coin] + 1, dp[i]);
}
}
return dp[amount] == amount + 1 ? -1 : dp[amount] ;
}
}