Maximize the Root

You are given a directed tree rooted at node 1 with n vertices. Every node has an initial non-negative value.

You can perform the following operation any number of times:

  • Choose a vertex v (it cannot be a leaf).
  • Increase the value of v by 1.
  • Decrease the value of ALL nodes in the subtree of v by 1.

Given an array a: length n representing the initial values of the nodes. a[i] is the initial value of Node i + 1 and an array p of length n - 1 representing the parent of each node. p[i] is the parent of Node i + 2. (e.g., p[0] is the parent of Node 2).

All node values must remain non-negative at all times.

Your task is to Maximize the value of the root (node 1) and output that maximum value.

Example 1:

Input: n = 4, a = [5, 2, 10, 20], p = [1, 1, 2]

Output: 20

Explanation: The tree is rooted at 1. Node 1 has children 2 and 3. Node 2 has child 4.

  • Node 4 is a leaf with value 20.
  • We can operate on node 2 up to 9 times. Its value becomes 2 + 9 = 11, and node 4 becomes 20 - 9 = 11.
  • Node 3 is a leaf with value 10.
  • Node 1 is the root. The minimum value in its children's subtrees is 10 (from node 3). We can operate on node 1 exactly 10 times. Its value becomes 5 + 10 = 15. Wait, we can actually operate on node 1 up to 15 times if we don't increase node 2 fully!
  • Maximum possible root value is 20

Example 2:

Input: n = 3, a = [5, 20, 10], p = [1, 2]

Output: 15

Explanation : Values already strictly decreasing (No operations beneficial except on root)

Now Your Turn!

Pick the correct output for the given input

Input : n = 4, a = [100, 5, 10, 0], p = [1, 1, 1]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 2 ≤ n ≤ 2 * 105
  • 0 ≤ a[i] ≤ 109
  •  1 ≤ p[i] < i + 2

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
long long maximizeRoot(vector<long long>& a, vector<int>& p) {
// Write your code here
return 0;
}
};
Test Case

Input:

A
P