-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
47 lines (40 loc) · 1.15 KB
/
Copy pathSolution.java
File metadata and controls
47 lines (40 loc) · 1.15 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package org.example.problems.coin_change;
import org.example.problems.SolutionInterface;
public class Solution implements SolutionInterface {
@Override
public String getName() {
return "Coin Change";
}
@Override
public String getUrl() {
return "https://leetcode.com/problems/coin-change/";
}
public int coinChange(int[] coins, int amount) {
if (amount == 0) {
return 0;
}
int[] sums = new int[amount + 1];
int minimalCoin = Integer.MAX_VALUE;
for (int c: coins) {
if (c < minimalCoin) {
minimalCoin = c;
}
if (c <= amount) {
sums[c] = 1;
}
}
for (int i = minimalCoin; i <= amount; i++) {
int min = sums[i];
for (int c: coins) {
int prev = i > c
? sums[i - c]
: 0;
if (prev != 0 && (prev + 1 < min || min == 0)) {
min = prev + 1;
}
}
sums[i] = min;
}
return sums[amount] == 0 ? -1 : sums[amount];
}
}