forked from kishanrajput23/Java-Projects-Collections
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExchange.java
38 lines (31 loc) · 1.11 KB
/
Exchange.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
import java.util.*;
public class Exchange {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the amount for Exchange: ");
int V = sc.nextInt();
exchanger(V);
sc.close();
}
public static void exchanger(int V) {
int[] coins = { 1, 2, 5, 10, 20, 50, 100, 200, 500, 2000 };
int[] minCoins = new int[V + 1];
int[] lastCoin = new int[V + 1];
for (int i = 1; i <= V; i++) {
minCoins[i] = Integer.MAX_VALUE;
for (int j = 0; j < coins.length; j++) {
if (coins[j] <= i && minCoins[i - coins[j]] + 1 < minCoins[i]) {
minCoins[i] = minCoins[i - coins[j]] + 1;
lastCoin[i] = coins[j];
}
}
}
System.out.println("Minimum number of coins: " + minCoins[V]);
System.out.print("Coins: ");
while (V > 0) {
System.out.print(lastCoin[V] + " ");
V -= lastCoin[V];
}
System.out.println();
}
}