ProgrammingHardInfosys · Cognizant

Coin denominations are 1, 4 and 6. The greedy method below pays amount 8 by always taking the largest coin that still fits (coins are reused). What is the number of coins printed?

Coin denominations are 1, 4 and 6. The greedy method below pays amount 8 by always taking the largest coin that still fits (coins are reused). What is the number of coins printed?
amount = 8; count = 0
for each coin in (6, 4, 1) from largest to smallest
    while amount >= coin: amount = amount - coin; count = count + 1
end for
Print count
  1. A. 3
  2. B. 8
  3. C. 2
  4. D. 1

Correct answer: A. 3

Largest first takes 6, then 1 and 1, for three coins. The optimum 4+4 uses two coins, ascending order takes eight 1s, and stopping after the first denomination pays only one coin.

More Pseudocode and Code Tracing questions

Exams that ask this topic