package username.dynamic; /** * A simple program to compute the fewest coins for a particular * price. * * @author Samuel A. Rebelsky * @author CSC152 2006S * @version 1.0 of April 2006 */ public class Coins { /** * Given a set of denominations, compute the fewest coins * for a particular price. */ public static int fewestCoins(int[] denominations, int price) throws Exception { // Sanity check if (price < 0) { throw new Exception("Invalid price"); } // Easy case: No cost implies no coins else if (price == 0) { return 0; } // Normal case: Check each coin and see which one works best. else { int best = Integer.MAX_VALUE; for (int i = 0; i < denominations.length; i++) { int newprice = price - denominations[i]; if (newprice >= 0) { try { int guess = fewestCoins(denominations, newprice); if (guess < best) { best = guess+1; } } // try catch (Exception e) { // Of well, that coin didn't work. } // catch(Exception } // if (newprice >= 0) } // for if (best != Integer.MAX_VALUE) { return best; } else { throw new Exception("Cannot make exact change for " + price); } } // normal case } // fewestCoins(int[], int) } // class Coins