ProgrammingModerateInfosys · Cognizant

Coin denominations are 1, 4 and 5. The greedy method for amount 8 considers denominations from largest to smallest and takes each coin while it still fits. What is printed?

Coin denominations are 1, 4 and 5. The greedy method for amount 8 considers denominations from largest to smallest and takes each coin while it still fits. What is printed?
amount = 8; count = 0
for each coin in (largest to smallest)
    while amount >= coin
        amount = amount - coin
        count = count + 1
    end while
end for
Print count
  1. A. 8
  2. B. 1
  3. C. 2
  4. D. 4

Correct answer: D. 4

Largest first takes 5 once and then three 1s, for four coins. Ascending order needs eight coins, and the optimum 4+4 (two coins) shows the greedy is not optimal for this coin set; stopping after the first denomination prints 1.

More Pseudocode and Code Tracing questions

Exams that ask this topic