KatInterview

Maximum Path Bonus in a Weighted Tree

Trees & GraphsAuto-graded · 15 test cases
MediumAuto-gradedTrees & Graphstreesdynamic-programmingtree-dp

Last updated

Tests tree DP (rerooting) by finding the node from which the maximum sum of weighted edges can be collected along any single root-to-leaf path in a tree.

Maximum Path Bonus in a Weighted Tree

You are given an undirected tree with n nodes numbered 0 to n - 1. Each edge carries an integer weight (which may be negative). Your task is to choose a root node and then collect the maximum sum of edge weights along any path from that chosen root down to any leaf in the resulting rooted tree.

Formally:

  • You are given the tree as a list of edges edges, where edges[i] = [u, v, w] means there is an edge between node u and node v with weight w.
  • You may pick any node as the root.
  • Once rooted, a leaf is any node with no children (i.e., degree-1 nodes other than the root; if n == 1, the single node is both root and leaf, and the answer is 0).
  • A root-to-leaf path is the unique path from the root down to a leaf in the rooted tree.
  • The path sum is the sum of all edge weights along that path.
  • You want to choose the root and a leaf (reachable from that root) to maximize the path sum.
  • Return this maximum achievable path sum as an integer.

Key clarifications:

  • If n == 1, return 0 (no edges to traverse).
  • If all path sums from every (root, leaf) pair are negative, return the least negative one (you must pick a root and must reach a leaf).
  • Weights can be zero, positive, or negative.
  • The tree is guaranteed to be connected.

Constraints

  • 1 <= n <= 2000
  • edges has exactly n - 1 elements.
  • Each edge is [u, v, w] where 0 <= u, v <= n - 1 and -1000 <= w <= 1000.
  • The given edges form a valid connected undirected tree.

Examples

Example 1

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

Output: 10

Example 2

Input: max_path_bonus(1, [])

Output: 0

Example 3

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

Output: -1

Hints

Hint 1

First think about what happens when you fix the root: you want the maximum sum along any root-to-leaf path, which you can find with a single DFS computing dp[node] = best sum achievable going deeper from node.

Hint 2

Notice that trying all n roots naively gives O(n²). Consider a rerooting technique: compute a 'downward' DP first, then propagate information back upward so each node can also consider the path going 'up' through its parent.

Hint 3

For a node v with parent p (edge weight w), the 'upward' best from v is: max(best going up from p, best going down from p through a sibling of v) + w. Combine downward and upward dp values carefully to handle leaves correctly.