-
-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathCoinChange.java
More file actions
27 lines (18 loc) · 602 Bytes
/
Copy pathCoinChange.java
File metadata and controls
27 lines (18 loc) · 602 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
package leetcode.medium;
public class CoinChange {
int coinChange(int[] coins, int amount) {
// Check edge case
if (amount < 1) return 0;
// Create DP array
int[] minCoinsDP = new int[amount + 1];
for (int i = 1; i <= amount; i++) {
minCoinsDP[i] = Integer.MAX_VALUE;
// Try each coin
for (int coin : coins) {
if (coin <= i && minCoinsDP[i - coin] != Integer.MAX_VALUE)
minCoinsDP[i] = Math.min(minCoinsDP[i], 1 + minCoinsDP[i - coin]);
}
}
return minCoinsDP[amount] == Integer.MAX_VALUE ? -1 : minCoinsDP[amount];
}
}