-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChangeMachine.java
More file actions
54 lines (46 loc) · 1.43 KB
/
ChangeMachine.java
File metadata and controls
54 lines (46 loc) · 1.43 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
package algorithm.greedyalgorithm;
import java.util.ArrayList;
/**
* The type Change machine.
*/
public class ChangeMachine {
/**
* The Coins.
*/
private static int[] coins = {25, 10, 5, 1};
/**
* Get change array list.
*
* @param amount the amount
* @return the array list
*/
public static ArrayList<Integer> getChange(int amount){
ArrayList<Integer> change = new ArrayList<>();
for (int i = 0; i < coins.length && amount > 0; i++) // traverse through all available coins
{
while (amount >= coins[i]) // keep checking if the amount is greater than the max coin
{
amount -= coins[i]; // subtract the maximum coin selected from the total amount in every iteration
change.add(coins[i]); // add the coin to the list of 'change'
}
}
return change;
}
/**
* Main.
*
* @param args the args
*/
public static void main(String args[])
{
// Play around with this amount to see how many coins you get!
int amount = 1;
System.out.println(amount + " --> " + getChange(amount));
amount = 17;
System.out.println(amount + " --> " + getChange(amount));
amount = 33;
System.out.println(amount + " --> " + getChange(amount));
amount = 99;
System.out.println(amount + " --> " + getChange(amount));
}
}