VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximal-point-path/

⇱ Maximal Point Path - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximal Point Path

Last Updated : 23 Jul, 2025

Given a tree with N nodes numbered from 1 to N. Each Node has a value denoting the number of points you get when you visit that Node. Each edge has a length and as soon as you travel through this edge number of points is reduced by the length of the edge, the task is to choose two nodes u and v such that the number of points is maximized at the end of the path from node u to node v.

Note: The number of points should not get negative in between the path from node u to node v.

Examples:

Input:

👁 Treedrawio-(1)

Output: Maximal Point Path in this case will be 2->1->3 and maximum points at the end of path will be (3-2+1-2+3) = 3

Input:


👁 Treedrawio-(2)

Output: Maximal Point Path in this case will be 2 -> 4 and maximum points at the end of path will be (3-1+5) = 7

Approach: This problem can be solved optimally using DP with trees concept.

Steps to solve the problem:

  • Root the tree at any node say (1).
  • For each of the nodes v in the tree, find the maximum points of the path passing through the node v. The answer will be the maximum of this value among all nodes in the tree.
  • To calculate this value for each node, maintain a dp array, where dp[v] is the maximal points of the path starting at node v for the subtree rooted at node v. dp[v] for a node v can be calculated from points[v] + max(dp[u] - wv->u ) where u is child of node v, wv->uis length of edge connecting node v and u and points[v] is the number points at the node v.
  • Now to find the maximum points of the path passing through the node v we calculate dp[u]-wv->u for each child of v and take the two biggest values from it and add points[v] in it.
  • If the maximum value of dp[u]-wv->u is negative then we will take 0 instead of it.

Below is the implementation of the above approach:


Output
7

Time Complexity: O(n*logn), since for each node sorting is performed on the values of its children.
Auxiliary Space : O(n), where n is the number of nodes in the tree.

Comment