Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Same robbery, but the houses form a circle (first and last are adjacent).

Problem: Same robbery, but the houses form a circle (first and last are adjacent).
def line(a):
    take = skip = 0
    for x in a:
        take, skip = skip + x, max(take, skip)
    return max(take, skip)
def circle(a):
    if len(a) == 1: return a[0]
    return max(line(a[1:]), line(a[:-1]))
print(circle([2, 3, 2]), circle([1, 2, 3, 1]), circle([5]))
What is printed?
  1. A. 4 4 5
  2. B. 3 4 0
  3. C. 3 3 5
  4. D. 3 4 5

Correct answer: D. 3 4 5

Run the line version twice – once without the first house, once without the last – so the two ends are never both taken. [2, 3, 2] → 3 (not 2 + 2 = 4). [1, 2, 3, 1] → 1 + 3 = 4. A single house must be handled separately, otherwise both slices are empty and the answer becomes 0. O(n).

More Coding Interview Problems questions

Exams that ask this topic