Course selection tree

Write codeHard40 min

Your task

You have a rooted tree of n courses (node 0 is the root). To take a course you must also take its parent (dependency). Each course i has a value val[i]. You may take at most k courses total. Return the maximum total value of a chosen connected subtree-respecting set that includes the constraint that a chosen node implies its parent is chosen. Equivalently: pick at most k nodes forming a set closed under 'take parent', maximizing value sum. Constraints: 1 <= n <= 300, 0 <= k <= n; parent[i] given for i>=1 (parent[i] < i); values may be negative.

Examples

max_value_with_deps(parent: list[int], val: list[int], k: int) -> int
Example 1
Inputmax_value_with_deps([-1, 0, 0, 1], [3, 4, 2, 5], 3)
Output12