Answer:
a) Proof:
1. Let’s consider the first two types of coins in this set, pennies and coins that are worth c cents each, which we will call c^ . At most, we can use c −1 pennies because any number larger than c pennies would be replaced by at least one c^ coin. This operation would reduce the total coin number by c −1. In other words, when the remainder is greater than c and I’m allowed to use only pennies and c^ coins, I would use as many c^ coins before considering pennies.
2. The same thoughts apply for larger coins. Let’s consider c^ n-1 and \hat{c}n coins. At most, we can use c −1 c^ n-1 coins. Because any number larger than cn would be replaced by at least one \hat{c}n coin. This operation would reduce the total coin number by c −1. In other words, when the remainder is greater than c^ n and I’m allowed to use only coins that are worth less than c^ n , I would use as many \hat{c}n coins as possible before considering other coins.
3. Combining the first two arguments, the greedy algorithm applies to all the levels of this particular coin set denomination.
b) The greedy algorithm always provides a solution but doesn’t guarantee the smallest number of coins used. The greedy algorithm takes O(nk ) for any kind of coin set denomination, where k is the number of different coins in a particular set. The algorithm is implemented below in Java:
/** * Makes change using a recursive Greedy algorithm. * * param amount * The amount of change to make. * param coins * The sorted set of coins, ordered from smallest to largest. * return The number of coins used to make the change. */ int makeChangeGreedyStyle(int amount, int[] coins) { // Check if there is no more change to make. if (amount == 0) { System.out.println(""); return 0; } // Loop over the change in order of greatest to smallest. for (int i = coins.length; i > 0; i--) { int coin = coins[i - 1]; // If the next largest coin is found, print out its value. if (amount >= coin) { System.out.print(coin + " "); return 1 + makeChangeGreedyStyle(amount - coin, coins); } } // Arriving here means it's impossible to make change // using this greedy algorithm, this amount of change, // and this set of coins. System.out.print("Cannot make change; "); System.out.println("cents remaining: " + amount); return 0; }
Step-by-step explanation: