Data Structures & AlgorithmsVery hardProduct company OA

Maximum-weight independent set on a tree (no two chosen nodes adjacent) by tree DP returning (best if u taken, best if u skipped), compared with the 'alternate levels' heuristic. What is printed?

Maximum-weight independent set on a tree (no two chosen nodes adjacent) by tree DP returning (best if u taken, best if u skipped), compared with the 'alternate levels' heuristic. What is printed?
import sys
sys.setrecursionlimit(10000)
w = {1: 6, 2: 2, 3: 9, 4: 4, 5: 3, 6: 1, 7: 1}
kids = {1: [2, 3], 2: [4, 5], 3: [6, 7], 4: [], 5: [], 6: [], 7: []}
def go(u):
    take, skip = w[u], 0
    for c in kids[u]:
        t, s = go(c)
        take += s; skip += max(t, s)
    return take, skip
t, s = go(1)
levels = max(w[1] + w[4] + w[5] + w[6] + w[7], w[2] + w[3])
print(max(t, s), levels)
  1. A. 15 15
  2. B. 16 16
  3. C. 22 15
  4. D. 16 15

Correct answer: D. 16 15

take(u) = w(u) + Σ skip(child); skip(u) = Σ max(take, skip) of children – each child decides independently. Taking either all even levels {1, 4, 5, 6, 7} (15) or the odd level {2, 3} (11) is not optimal: {3, 4, 5} = 9 + 4 + 3 = 16 skips both 1 and 2 and mixes levels. 22 ignores the adjacency rule. O(n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic