Equalize Root-to-Leaf Sums in an N-ary Tree
A rooted tree has n nodes numbered 0 to n - 1. Node i holds the non-negative value values[i], and parents[i] is its parent; the root is node 0 with parents[0] = -1. A node may have any number of children.
In one operation you may increase the value of any single node by 1. Return the minimum number of operations needed to make the sum of values along every root-to-leaf path equal.
values = [2, 3, 4], parents = [-1, 0, 0] -> 1 // raise the 3 to 4 values = [1, 2, 3, 2, 2, 3, 3], parents = [-1, 0, 0, 1, 1, 2, 2] -> 2 // paths sum to 5, 5, 7, 7: raise node 1 twice, which fixes both of its leaves
Up to 200,000 nodes with values up to 1,000,000; the tree may be a long chain. The round asks you to write and run your own test cases.
Hints
Hint 1
Paths can only get longer, so every path must reach the largest path sum that already exists below each node.
Hint 2
Look at one node and its children. If the children's subtrees have already been equalised internally, each child subtree has a single path sum. What is the cheapest way to make those sums agree?
Hint 3
Raising a child by d raises every path through it by d at a cost of d. Raising its leaves instead would cost d per leaf.
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.