forked from iiitv/algos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CoinChangeProblem.java
39 lines (36 loc) · 1.19 KB
/
CoinChangeProblem.java
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
import java.util.Arrays;
public class CoinChangeProblem {
/**
* Implementation of famous dynamic programming problem
* that aims to find out the maximum number of ways in
* which a value can be achieved using some fixed valued
* coins.
*
* In the implementation, the time complexity is O(mn)
* and extra space required is O(n).
*
* @param coins
* @param n
* @return
*/
public static int coinChangeProblem(int[] coins, int value) {
int[] possibilities = new int[value + 1];
Arrays.fill(possibilities, 0);
possibilities[0] = 1;
// Build the possibilities table in bottom-up manner
// For all coins,
// Update array if the current coin is capable of
// incrementing the possibility
for (int i = 0; i < coins.length; i++) {
for (int j = coins[i]; j <= value; j++) {
possibilities[j] += possibilities[j - coins[i]];
}
}
return possibilities[value];
}
public static void main(String[] args) {
int[] coins = {2, 5, 3, 6};
int value = 10;
System.out.println(coinChangeProblem(coins, value));
}
}