ProgrammingHardGATE CS & IT · Infosys

What is printed?

What is printed?
def rob(a):
    p, c = 0, 0
    for x in a:
        p, c = c, max(c, p + x)
    return c
print(rob([2, 7, 9, 3, 1]), rob([5]), rob([]))
  1. A. 11 5 0
  2. B. 12 5 0
  3. C. 12 5 5
  4. D. 12 0 0

Correct answer: B. 12 5 0

The best non-adjacent subset of [2,7,9,3,1] is 2 + 9 + 1 = 12. Empty input gives 0 and a single item gives its own value.

More Python Programming questions

Exams that ask this topic