Subtree Pruning III
The same tree shape: n nodes, a parent array with parent[0] = -1, node 0 the root at depth 0. Deleting a node removes it and its whole subtree.
Now any non-root node may be deleted, whether or not it is within the limit. First use the fewest deletions that leave every remaining node at depth at most maxDepth; among those plans, choose the one whose deleted nodes have the largest total original depth.
Return [deletions, depthSum].
bestCuts(5, [-1, 0, 1, 2, 3], 2) -> [1, 3] // cut node 3 (depth 3) rather than node 1 or 2 bestCuts(7, [-1, 0, 0, 1, 1, 2, 5], 2) -> [1, 3] // 2, 5 or 6 would do; 6 is deepest bestCuts(1, [-1], 0) -> [0, 0]
Hints
Hint 1
A root branch that holds any too-deep node needs at least one cut, and one cut at the branch's top is always enough — so the minimum is the number of such branches.
Hint 2
To push a branch's single cut as deep as possible, descend while all of the branch's too-deep nodes still sit under one child.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.