KatInterview

Maximum Path Gain in a Weighted Tree

Trees & GraphsAuto-graded · 17 test cases
MediumAuto-gradedTrees & Graphstreesdynamic programmingdepth-first search

Last updated

Tests tree DP on a weighted tree to find the maximum sum of node values along any root-to-leaf path, using depth-first traversal and subproblem combination.

Maximum Path Gain in a Weighted Tree

You are given a weighted, rooted tree with n nodes numbered 0 to n-1. Node 0 is always the root.

The tree is described by a list of edges, where each edge is [u, v, w] meaning there is an undirected edge between node u and node v with integer weight w.

Your task is to find the maximum total weight along any root-to-leaf path.

A root-to-leaf path starts at node 0 and ends at a node that has no children (i.e., a leaf). The total weight of a path is the sum of all edge weights along that path.

Return the maximum such sum. If the tree has only the root and no edges (a single node), return 0.

Definitions:

  • A leaf is any node with degree 1 in the tree except the root (node 0), even if the root itself has degree 1 (i.e., the root is never considered a leaf unless n == 1).
  • When n == 1, there are no edges and the only path is the trivial root-only path with sum 0.

Constraints

  • 1 ≤ n ≤ 2000
  • edges has exactly n - 1 entries (the graph is always a valid tree).
  • Each edge is [u, v, w] where 0 ≤ u, v ≤ n-1 and -1000 ≤ w ≤ 1000.
  • The graph is connected.
  • Weights may be negative.

Examples

Example 1

Input: max_root_to_leaf_gain(1, [])

Output: 0

Example 2

Input: max_root_to_leaf_gain(4, [[0, 1, 3], [1, 2, 1], [1, 3, -2]])

Output: 4

Example 3

Input: max_root_to_leaf_gain(6, [[0, 1, 5], [0, 2, 2], [2, 3, 4], [2, 4, -1], [1, 5, 3]])

Output: 8

Hints

Hint 1

Build an adjacency list from the edge list, then do a DFS from node 0 keeping track of the parent to avoid revisiting.

Hint 2

At each node, if it is a leaf (no unvisited children), its contribution to the answer is the accumulated path sum so far.

Hint 3

Use a recursive DFS where the return value is the maximum root-to-leaf sum in the subtree rooted at that node; combine children results by taking the max.