ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (All variables are integers, so / is integer division)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division)
Integer dp[0..10]
dp[1] = 0
for (each i from 2 to 10)
    dp[i] = dp[i - 1] + 1
    if (i mod 2 == 0) dp[i] = min(dp[i], dp[i / 2] + 1)
    if (i mod 3 == 0) dp[i] = min(dp[i], dp[i / 3] + 1)
end for
Print dp[10]
  1. A. 4
  2. B. 2
  3. C. 5
  4. D. 3

Correct answer: D. 3

dp[i] is the fewest steps to reach 1 using −1, ÷2, ÷3. The best path for 10 is 10 → 9 → 3 → 1 (3 steps). Halving first, as a greedy rule would, gives 10 → 5 → 4 → 2 → 1 (4 steps).

More Pseudocode and Code Tracing questions

Exams that ask this topic