ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Function rob(Integer a[], Integer lo, Integer hi)
    Integer inc = 0, exc = 0, t
    for (each i from lo to hi)
        t = max(inc, exc)
        inc = exc + a[i]
        exc = t
    end for
    return max(inc, exc)
End Function
Integer h[5] = {2, 7, 9, 3, 1}
Print rob(h, 0, 4), max(rob(h, 0, 3), rob(h, 1, 4))
  1. A. 12 12
  2. B. 11 11
  3. C. 12 10
  4. D. 12 11

Correct answer: D. 12 11

In a row, the best non-adjacent pick is 2 + 9 + 1 = 12. If the houses form a circle, the first and last are neighbours, so solve without the last (best 2 + 9 = 11) and without the first (best 7 + 3 = 10, or 9 + 1 = 10): 11. Output 12 11.

More Pseudocode and Code Tracing questions

Exams that ask this topic