Given an undirected tree with n nodes numbered from 1 to n and an array arr[] where arr[i] denotes the value assigned to (i+1)th node. The connections between the nodes are provided in a 2-dimensional array edges[][]. The task is to find the maximum path sum between any two nodes. (Both the nodes can be the same also).
Note: The path sum is equal to the sum of the value of the nodes of that path.
Examples:
Input: arr[] = [4, -1, -3, 5, 7, -2], edges[][] = [[1, 2], [1, 3], [2, 4], [2, 5], [2, 6]] Output: 11 Explanation: The maximum path sum will between node 4 and 5 through node 2. i.e., 5 - 1 + 7 = 11
Input: arr[] = [2, 3, 4], edges[][] = [[1, 2], [1, 3]] Output: 9 Explanation: The maximum path sum will between all the nodes i.e., 2 + 3 + 4 = 9
Approach:
The idea is to calculate the maximum path sum for each node by finding the two longest paths starting from that node and reaching its descendants. The maximum path sum for a node is the sum of its value and the two largest path sums from its children. The algorithm uses depth-first search to explore all nodes, avoiding cycles by keeping track of the parent node. The maximum path sum is updated whenever a larger sum is found.
C++
// C++ code to find maximum path sum// in a N-ary tree.#include<bits/stdc++.h>usingnamespacestd;intmaxSumRecur(intnode,intprev,vector<vector<int>>&adj,vector<int>&arr,int&ans){intmaxi1=0,maxi2=0;// Traverse all child nodes of the current nodefor(autov:adj[node]){// Skip the parent node to avoid cyclesif(v!=prev){intval=maxSumRecur(v,node,adj,arr,ans);if(val>maxi1){maxi2=maxi1;maxi1=val;}elseif(val>maxi2){maxi2=val;}}}// Update the answer with the best path sumans=max(ans,arr[node-1]+maxi1+maxi2);// Return the maximum path sum starting// at this node, considering its subtreereturnarr[node-1]+maxi1;}intmaxSum(vector<vector<int>>&edges,vector<int>&arr){intn=arr.size();vector<vector<int>>adj(n+1);for(autoedge:edges){adj[edge[0]].push_back(edge[1]);adj[edge[1]].push_back(edge[0]);}intans=0;maxSumRecur(1,-1,adj,arr,ans);returnans;}intmain(){vector<int>arr={4,-1,-3,5,7,-2};vector<vector<int>>edges={{1,2},{1,3},{2,4},{2,5},{2,6}};cout<<maxSum(edges,arr);return0;}
Java
// Java code to find maximum path sum// in a N-ary tree.importjava.util.*;classGfG{staticintmaxSumRecur(intnode,intprev,ArrayList<ArrayList<Integer>>adj,int[]arr,int[]ans){intmaxi1=0,maxi2=0;// Traverse all child nodes of the current nodefor(intv:adj.get(node)){// Skip the parent node to avoid cyclesif(v!=prev){intval=maxSumRecur(v,node,adj,arr,ans);if(val>maxi1){maxi2=maxi1;maxi1=val;}elseif(val>maxi2){maxi2=val;}}}// Update the answer with the best path sumans[0]=Math.max(ans[0],arr[node-1]+maxi1+maxi2);// Return the maximum path sum starting// at this node, considering its subtreereturnarr[node-1]+maxi1;}staticintmaxSum(int[][]edges,int[]arr){intn=arr.length;ArrayList<ArrayList<Integer>>adj=newArrayList<>(n+1);// Create adjacency listfor(inti=0;i<=n;i++){adj.add(newArrayList<>());}for(int[]edge:edges){adj.get(edge[0]).add(edge[1]);adj.get(edge[1]).add(edge[0]);}int[]ans={0};maxSumRecur(1,-1,adj,arr,ans);returnans[0];}publicstaticvoidmain(String[]args){int[]arr={4,-1,-3,5,7,-2};int[][]edges={{1,2},{1,3},{2,4},{2,5},{2,6}};System.out.println(maxSum(edges,arr));}}
Python
# Python code to find maximum path sum# in a N-ary tree.defmaxSumRecur(node,prev,adj,arr,ans):maxi1=0maxi2=0# Traverse all child nodes of the current nodeforvinadj[node]:# Skip the parent node to avoid cyclesifv!=prev:val=maxSumRecur(v,node,adj,arr,ans)ifval>maxi1:maxi2=maxi1maxi1=valelifval>maxi2:maxi2=val# Update the answer with the best path sumans[0]=max(ans[0],arr[node-1]+maxi1+maxi2)# Return the maximum path sum starting# at this node, considering its subtreereturnarr[node-1]+maxi1defmaxSum(edges,arr):n=len(arr)adj=[[]for_inrange(n+1)]# Create adjacency listforedgeinedges:adj[edge[0]].append(edge[1])adj[edge[1]].append(edge[0])ans=[0]maxSumRecur(1,-1,adj,arr,ans)returnans[0]if__name__=="__main__":arr=[4,-1,-3,5,7,-2]edges=[[1,2],[1,3],[2,4],[2,5],[2,6]]print(maxSum(edges,arr))
C#
// C# program to find Maximum // Path sum in a N-ary TreeusingSystem;usingSystem.Collections.Generic;classGfG{staticintmaxSumRecur(intnode,intprev,List<List<int>>adj,int[]arr,refintans){intmaxi1=0,maxi2=0;// Traverse all child nodes of the current nodeforeach(intvinadj[node]){// Skip the parent node to avoid cyclesif(v!=prev){intval=maxSumRecur(v,node,adj,arr,refans);if(val>maxi1){maxi2=maxi1;maxi1=val;}elseif(val>maxi2){maxi2=val;}}}// Update the answer with the best path sumans=Math.Max(ans,arr[node-1]+maxi1+maxi2);// Return the maximum path sum starting // at this node, considering its subtreereturnarr[node-1]+maxi1;}staticintmaxSum(int[,]edges,int[]arr){intn=arr.Length;List<List<int>>adj=newList<List<int>>(newList<int>[n+1]);// Create adjacency listfor(inti=0;i<=n;i++){adj[i]=newList<int>();}for(inti=0;i<edges.GetLength(0);i++){adj[edges[i,0]].Add(edges[i,1]);adj[edges[i,1]].Add(edges[i,0]);}intans=0;maxSumRecur(1,-1,adj,arr,refans);returnans;}staticvoidMain(string[]args){int[]arr={4,-1,-3,5,7,-2};int[,]edges={{1,2},{1,3},{2,4},{2,5},{2,6}};Console.WriteLine(maxSum(edges,arr));}}
JavaScript
// JavaScript program to find// Maximum Path sum in a N-ary TreefunctionmaxSumRecur(node,prev,adj,arr,ans){letmaxi1=0,maxi2=0;// Traverse all child nodes of the current nodefor(letvofadj[node]){// Skip the parent node to avoid cyclesif(v!==prev){letval=maxSumRecur(v,node,adj,arr,ans);if(val>maxi1){maxi2=maxi1;maxi1=val;}elseif(val>maxi2){maxi2=val;}}}// Update the answer with the best path sumans[0]=Math.max(ans[0],arr[node-1]+maxi1+maxi2);// Return the maximum path sum starting// at this node, considering its subtreereturnarr[node-1]+maxi1;}functionmaxSum(edges,arr){letn=arr.length;letadj=Array.from({length:n+1},()=>[]);// Create adjacency listfor(letedgeofedges){adj[edge[0]].push(edge[1]);adj[edge[1]].push(edge[0]);}letans=[0];maxSumRecur(1,-1,adj,arr,ans);returnans[0];}letarr=[4,-1,-3,5,7,-2];letedges=[[1,2],[1,3],[2,4],[2,5],[2,6]];console.log(maxSum(edges,arr));
Output
11
Time Complexity: O(n) , where n is the number of nodes in the tree. Auxiliary Space: O(n)