VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-path-sum-in-a-n-ary-tree/

⇱ Maximum Path sum in a N-ary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Path sum in a N-ary Tree

Last Updated : 23 Jul, 2025

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

👁 Maximum-Path-sum-in-a-N-ary-Tree-1


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

👁 Maximum-Path-sum-in-a-N-ary-Tree-2

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.


Output
11

Time Complexity: O(n) , where n is the number of nodes in the tree.
Auxiliary Space: O(n)

Comment