Maximum Average N-ary Subtree
Problem statement
An n-ary tree has nodes 0 through n - 1. Node 0 is the root, parent[0] = -1, and parent[i] is the parent of every other node. Node i has integer value values[i].
The subtree rooted at a node contains that node and all its descendants. Consider only roots with at least one child. Return the index of the candidate subtree with the greatest average node value. Compare averages exactly. If several candidates tie, return the smallest root index. Return -1 if there is no candidate.
Function
maximumAverageSubtree(parent: int[], values: int[]) → intExamples
Example 1
parent = [-1,0,0,1,1,1,2,2]values = [20,12,18,11,2,3,15,8]return = 2The averages at candidate roots 0, 1, and 2 are 89/8, 28/4, and 41/3. Node 2 is best.
Example 2
parent = [-1,0,0,1]values = [0,0,0,0]return = 0Both candidate roots 0 and 1 have average zero. The smaller index wins.
Constraints
1 <= n == parent.length == values.length <= 20000.- The parent array describes one valid tree rooted at 0; a parent index need not be smaller than its child index.
-10000 <= values[i] <= 10000.