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)- A. 15 15
- B. 16 16
- C. 22 15
- 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- BFS that also counts the number of shortest paths. What is printed (dist[7], ways[7], ways[6], ways[4])? python from collections import…
- Dijkstra with a binary heap and lazy deletion (no decrease-key; outdated entries are skipped when popped). What is printed (dist to E…
- AVL insertions (rotations labelled by imbalance case). What is printed (preorder, rotation cases in order, height in edges)? python class…
- B-tree with minimum degree t = 2 (a 2-3-4 tree, at most 3 keys per node) using the single-pass insertion that splits every FULL node on…
- Building a min-heap from [9, 8, 7, 6, 5, 4, 3]: (a) seven sift-up insertions, (b) bottom-up heapify. What is printed (heaps and swap…
- Exact count of the innermost statement for n = 30 (j advances by i, k advances by j). What is printed? python c = 0 n = 30 for i in…