-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMInCoins.java
More file actions
59 lines (54 loc) · 1.39 KB
/
MInCoins.java
File metadata and controls
59 lines (54 loc) · 1.39 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
48
49
50
51
52
53
54
55
56
57
58
59
package algorithm.DynamicProgramming;
import java.util.Arrays;
/**
* The type M in coins.
*/
public class MInCoins {
/**
* Gets min coins.
*
* @param a the a
* @param sum the sum
* @return the min coins
*/
public static int getMinCoins(int a[], int sum) {
int dp[] = new int[sum];
Arrays.fill(dp, -1);
return getMinCoinHelper(a, sum, dp);
}
/**
* Gets min coin helper.
*
* @param a the a
* @param sum the sum
* @param dp the dp
* @return the min coin helper
*/
public static int getMinCoinHelper(int a[], int sum, int dp[]) {
if (sum == 0) return 0;
int ans = Integer.MAX_VALUE;
for (int i : a) {
if (sum - i >= 0) {
int subAns = 0;
if (dp[sum - i] != -1) {
subAns = dp[sum - i];
} else {
subAns = getMinCoins(a, sum - i);
}
if (subAns + 1 < ans && subAns != Integer.MAX_VALUE)
ans = subAns + 1;
}
}
return ans;
}
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args) {
int sum = 18;
int a[] = {1, 5, 7};
System.out.println("Coins required is " + getMinCoins(a, sum));
}
}