All problems
Tree DP Maximum Independent Set
Problem
Compute the size of a maximum independent set of a tree with dynamic programming.
Root the tree at node 0. For each node keep take[v] = 1 + sum of skip over children and skip[v] = sum of max(take, skip) over children, processing nodes in reverse BFS order. edges is a list of [u, v] pairs. Return the best value at the root.
Hint
A node taken forces every child skipped, but a skipped node lets each child choose freely.
Test cases
case 1
in: [4,[[0,1],[1,2],[2,3]]]
expected: 2
case 2
in: [4,[[0,1],[0,2],[0,3]]]
expected: 3
case 3
in: [1,[]]
expected: 1
case 4
in: [5,[[0,1],[1,2],[1,3],[3,4]]]
expected: 3
case 5
in: [3,[[0,1],[1,2]]]
expected: 2
Starter codePython
def tree_dp_max_independent_set(n, edges):
# Your code here
pass5 test cases · run your code against them in the editor