Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Rob houses arranged as a tree (node 0 is the root; parent[i] gives each node's parent). Directly linked houses cannot both be robbed.

Problem: Rob houses arranged as a tree (node 0 is the root; parent[i] gives each node's parent). Directly linked houses cannot both be robbed.
val = [2, 9, 3, 7, 1, 4, 5]
parent = [-1, 0, 0, 1, 1, 2, 2]
kids = [[] for _ in val]
for i, p in enumerate(parent):
    if p >= 0: kids[p].append(i)
def go(u):
    take, skip = val[u], 0
    for c in kids[u]:
        t, s = go(c)
        take += s; skip += max(t, s)
    return take, skip
print(max(go(0)))
What is printed?
  1. A. 18
  2. B. 19
  3. C. 21
  4. D. 12

Correct answer: B. 19

Each node returns (take, skip): taking the root 2 plus the four leaves 7, 1, 4, 5 gives 19, while the best without the root is max(9, 8) + max(3, 9) = 18. Greedily grabbing the largest value 9 gives 18; treating val as a linear street (house robber on the array) gives 21; taking the whole middle level 9 + 3 gives 12.

More Coding Interview Problems questions

Exams that ask this topic