Determine the minimum number of coins for change


/ Published in: Java
Save to your folder(s)

Determine the minimum number of coins for change
Given any number between 1 and 99, determine how to give change with the minimum number of coins. You can assume that the coins are 1c, 2c, 5c, 10c, 20c and 50c.


Copy this code and paste it in your HTML
  1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3. import java.util.List;
  4. import java.util.Map;
  5.  
  6. public class ChangeCalculator {
  7.  
  8. /**
  9.   * @param args
  10.   */
  11. public static void main(String[] args) {
  12. /*Scanner scn = new Scanner(System.in);
  13.   Integer amount = scn.nextInt();*/
  14. Integer amount = 105;
  15. Map<String, Integer> changeMap = getChange(amount);
  16. System.out.println(changeMap);
  17.  
  18. }
  19.  
  20. private static Map<String, Integer> getChange(Integer amount) {
  21. Map<String, Integer> changeMap = new HashMap<String, Integer>();
  22. List<Integer> changeList = new ArrayList<Integer>();
  23. changeList.add(50);
  24. changeList.add(20);
  25. changeList.add(10);
  26. changeList.add(5);
  27. changeList.add(2);
  28. changeList.add(1);
  29. Integer remAmt = amount;
  30. for (Integer change : changeList) {
  31. Integer changeCount = (remAmt / change);
  32. changeMap.put(change+"c", changeCount);
  33. remAmt = remAmt - (changeCount*change);
  34. }
  35. return changeMap;
  36. }
  37.  
  38. //private static
  39.  
  40. }

URL: http://java.dzone.com/articles/thursday-code-puzzler-change

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.