In a company, there are employees labelled . The organizational structure of the company forms a tree-like hierarchy.
We say that employee is the subordinate of employee, if employee appears in a subtree rooted at .
Your task is to find a pair of employees , a subordinate of , such that is maximized. Enter your answer as the value of .
Here is the data.
1 2 3 |
|
Expected Output:
6
Explanation : In this case, the possible choices to consider are (2,1) with a difference in wealth of of 5, (2,3) with 4, (2,4) with -2 and (4,3) with 6. So the answer is 6.
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
The simplest way to solve this problem is to consider all pairs ( i , j ) where j is a subordinate of i . To do this, we could pick each node and climb upto the root whilst keeping track of the maximum difference.
Clearly, this is a O ( N ⋅ h ) solution where h stands for height. For a random tree, this tends to be O ( N lo g N ) , however in the worst case, i.e, when the tree is a long chain, the complexity becomes O ( N 2 ) .
Turns out we can do better.
Notice that the maximum difference between a fixed node i and some node j in its subtree can be found by simply finding the minimum value in the subtree, which can be done using a DFS.
So, the key is to use a DFS to get the minimum at each subtree and for each node, check if the maximum possible difference from this node to the minimum in the corresponding subtree is greater than what we've encountered so far.
This is an O ( N ) solution since we run the processing at each node only once.