Data Structures and Algorithms
You pay 8 yen with coins of 1 yen, 4 yen and 6 yen. Which correctly relates the number of coins chosen by a greedy algorithm, which uses as many of the largest coin as possible first, to the minimum number of coins?
- AThe greedy algorithm also reaches the minimum of 2 coins
- BThe greedy algorithm uses 3 coins and misses the minimum of 2
- CThe greedy algorithm uses 3 coins, and that is the minimum
Show answer and explanation
Answer: B. The greedy algorithm uses 3 coins and misses the minimum of 2
The greedy algorithm first takes one 6-yen coin and pays the remaining 2 yen with two 1-yen coins, for 3 coins. But two 4-yen coins pay it with just 2. Because a greedy algorithm only accumulates the choice that looks best at each moment, it is not optimal for some coin systems. Dynamic programming, which fills in a table of the minimum number of coins for every amount from 0 to 8 yen in increasing order, always finds the minimum. For coin systems such as Japan's 1, 5, 10, 50, 100 and 500 yen, the greedy algorithm always gives the minimum.
- A. The greedy algorithm picks the 6-yen coin first, so it never reaches the two-4-yen combination.
- B. Correct. Greedy gives 6 + 1 + 1, three coins; the minimum is 4 + 4, two coins.
- C. Two 4-yen coins pay it with 2 coins, so 3 is not the minimum.