Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Houses stand in a CIRCLE (the first and last are neighbours); adjacent houses cannot both be robbed.

Problem: Houses stand in a CIRCLE (the first and last are neighbours); adjacent houses cannot both be robbed.
def rob_line(a):
    take = skip = 0
    for x in a: take, skip = skip + x, max(take, skip)
    return max(take, skip)
def rob_circle(a):
    if len(a) == 1: return a[0]
    return max(rob_line(a[:-1]), rob_line(a[1:]))
print(rob_circle([6, 2, 9, 4, 7]), rob_line([6, 2, 9, 4, 7]))
What is printed?
  1. A. 22 22
  2. B. 15 22
  3. C. 16 22
  4. D. 16 16

Correct answer: C. 16 22

In a line, 6 + 9 + 7 = 22 is best, but in a circle 6 and 7 are neighbours. Excluding the last house gives 6 + 9 = 15; excluding the first gives 9 + 7 = 16, so the circle answer is 16.

More Coding Interview Problems questions

Exams that ask this topic