-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoin Change Problem
More file actions
60 lines (46 loc) · 1.81 KB
/
Copy pathCoin Change Problem
File metadata and controls
60 lines (46 loc) · 1.81 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
60
//Coin Change Problem
import java.util.*;
public class CoinChange {
// Memoization array to store results for subproblems
private static int[] memo;
public static int coinChange(int[] coins, int amount) {
// Initialize memo array with -2 (indicates uncalculated)
memo = new int[amount + 1];
Arrays.fill(memo, -2);
// Call recursive helper function
int result = helper(coins, amount);
// If result is a large number, return -1 (not possible)
return result == Integer.MAX_VALUE ? -1 : result;
}
// Recursive helper function to find min coins for current amount
private static int helper(int[] coins, int amount) {
// Base case: if amount is 0, no coins needed
if (amount == 0) return 0;
// Base case: negative amount means no solution
if (amount < 0) return Integer.MAX_VALUE;
// Return cached result if already computed
if (memo[amount] != -2) return memo[amount];
int minCoins = Integer.MAX_VALUE;
// Try every coin and choose the one with minimum coins
for (int coin : coins) {
int res = helper(coins, amount - coin);
if (res != Integer.MAX_VALUE) {
minCoins = Math.min(minCoins, res + 1);
}
}
// Store the computed result in memo and return
memo[amount] = minCoins;
return minCoins;
}
// Main method to test the code
public static void main(String[] args) {
int[] coins = {1, 2, 5};
int amount = 11;
int result = coinChange(coins, amount);
if (result == -1) {
System.out.println("It is not possible to make the amount with given coins.");
} else {
System.out.println("Minimum coins needed: " + result);
}
}
}