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[3] = {1, 2, 5}
Integer ways[0..6] = all 0
ways[0] = 1
for (each a from 1 to 6)
    for (each i from 0 to 2)
        if (coins[i] <= a)
            ways[a] = ways[a] + ways[a - coins[i]]
        end if
    end for
end for
Print ways[6]
  1. A. 5
  2. B. 15
  3. C. 13
  4. D. 8

Correct answer: B. 15

With the amount in the OUTER loop, ways[a] counts ordered sequences of coins (1 + 2 and 2 + 1 differ): ways = 1, 1, 2, 3, 5, 9, 15 for 0 to 6. The usual coin-change count (5 unordered ways) needs the coin loop outside.

More Pseudocode and Code Tracing questions

Exams that ask this topic