Data Structures & AlgorithmsHardProduct Company SDE · DP round

Problem: Houses in a circle hold the amounts [2, 3, 2]. You may not rob two adjacent houses, and the first and last are adjacent. Run the code. What is printed?

Problem: Houses in a circle hold the amounts [2, 3, 2]. You may not rob two adjacent houses, and the first and last are adjacent. Run the code. What is printed?
def rob_line(a):
    p = q = 0
    for x in a:
        p, q = q, max(q, p + x)
    return q
a = [2, 3, 2]
print(max(rob_line(a[:-1]), rob_line(a[1:])))
What is printed?
  1. A. 3
  2. B. 4
  3. C. 5
  4. D. 2

Correct answer: A. 3

Robbing the first and last house together is forbidden, so the answer is the better of the two linear problems: [2, 3] gives 3 and [3, 2] gives 3. Robbing 2 + 2 = 4 would break the adjacency rule.

More Coding Interview Problems questions

Exams that ask this topic