Question asked in Google online coding challenge on 22nd AUG, 2020.
Please help me with this question.
You are given a tree with N nodes numbered 1 to N. Each node is having weight Ai. (1 <= i <= N)
Find the maximum path sum between any two node u and v of the tree. Return the maximum path sum value. constraints:
1 <= T <= 10
1 <= N <= 1e4
-1e6 <= Ai <= +1e6
Example:
A simple DP should work ig.
It can be solved using dynamic programming on trees. Refer the following link to find maximum path sum of a binary tree : https://www.geeksforgeeks.org/find-maximum-path-sum-in-a-binary-tree/
For a normal tree, we just need a little bit of manipulation,
Let $$$dp1[i]$$$=maximum path only includes node 'i', $$$dp2[i]$$$=maximum path that passes through node 'i' and one of its children. $$$dp3[i]$$$=maximum path that passes through node 'i' and two of its children. Now, $$$dp1[i]=a[i]$$$
$$$dp2[i]=a[i] + max(dp1[v1],dp2[v1],.............dp1[vk],dp2[vk]) $$$,
where $$$(v1,v2,....vk)$$$ are children of node "i".
Similarly, $$$dp3[i]$$$ can be calculated.
Final answer is maximum of all the $$$dps$$$ from $$$i=1$$$ to $$$N$$$
Time Complexity : $$$O(N)$$$
I'm not exactly sure but we can flat tree and at in time value will be a[i] and at out time value will be -a[i].Now we can just apply kadane's algorithm to find largest sum,but starting point should be in point only and ending point is also in point,also starting point and ending points should be different,by different I mean that we should select at least two points.
this was my working submission for this question