ProgrammingHardInfosys · Cognizant

Coins are 1, 5, 10, 21 and 25. To pay 63, the greedy method below always takes the largest coin that fits, using the list in descending order. What is the number of coins printed?

Coins are 1, 5, 10, 21 and 25. To pay 63, the greedy method below always takes the largest coin that fits, using the list in descending order. What is the number of coins printed?
amount = 63; coins = 0
for d in (25, 21, 10, 5, 1), largest first
    k = amount div d; coins = coins + k; amount = amount - k * d
end for
Print coins
  1. A. 63
  2. B. 7
  3. C. 3
  4. D. 6

Correct answer: D. 6

Greedy takes 25, 25, then 10, then 1, 1, 1 for six coins, while 21+21+21 uses only three. Ascending order takes sixty-three 1s, dropping the 10 coin gives 7 coins, and the true optimum 21+21+21 (three coins) is what the greedy misses.

More Pseudocode and Code Tracing questions

Exams that ask this topic