Choose Non-Adjacent Tree Values
Return two answers from every subtree, with the node taken and with it skipped, and combine them at the parent.
The problem
Implement maximum_tree_independent_sum(parents, values). A tree has n nodes numbered 0 to n - 1. Node 0 is the root, so parents[0] is -1, and for every other node i, parents[i] is its parent. values[i] is the value of node i and is never negative. Pick a set of nodes so that no node is picked together with its parent, and return the largest possible sum of the picked values. For example, for the chain 0 - 1 - 2 - 3 with values [2, 7, 4, 6], picking nodes 1 and 3 gives 13.
Starter code
def maximum_tree_independent_sum(parents, values):
passPublic examples
parents = [-1, 0, 0, 1, 1], values = [4, 2, 3, 5, 1]gives10parents = [-1, 0, 1, 2], values = [2, 7, 4, 6]gives13
Solving it in the practice book needs an active paid plan.
Open it in the practice bookOne thought at a time.
