ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer coins[4] = {9, 6, 5, 1}      // sorted largest first
Integer amt = 11, used = 0
for (each i from 0 to 3)
    while (amt >= coins[i])
        amt = amt - coins[i]
        used = used + 1
    end while
end for
Print used
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 11

Correct answer: A. 3

The greedy method takes 9 and then 1 + 1: 3 coins. It is not optimal here: 6 + 5 makes 11 with only 2 coins. Greedy is safe for systems like 1, 2, 5, 10 but not for every set of coins.

More Pseudocode and Code Tracing questions

Exams that ask this topic