Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Maximum independent set (largest set of pairwise non-adjacent nodes) in a TREE with a two-state DP.

Problem: Maximum independent set (largest set of pairwise non-adjacent nodes) in a TREE with a two-state DP.
from collections import defaultdict
E = [(0,1),(0,2),(1,3),(1,4),(2,5),(5,6),(5,7),(7,8)]
g = defaultdict(list)
for u, v in E: g[u].append(v); g[v].append(u)
def go(u, p):
    take, skip = 1, 0
    for v in g[u]:
        if v != p:
            t, s = go(v, u); take += s; skip += max(t, s)
    return take, skip
print(max(go(0, -1)))
What is printed?
  1. A. 4
  2. B. 6
  3. C. 9
  4. D. 5

Correct answer: D. 5

take = 1 + Σ skip(child), skip = Σ max(child). Leaves 3, 4 and 6, 8 are always worth taking; then 2 can be added (its child 5 is excluded because of 6) — e.g. {3, 4, 2, 6, 8} = 5. Greedy 'take all leaves' happens to be optimal here but not in general.

More Coding Interview Problems questions

Exams that ask this topic