Maximum Path Bonus in a Weighted Tree
Trees & GraphsAuto-graded · 15 test casesLast 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, whereedges[i] = [u, v, w]means there is an edge between nodeuand nodevwith weightw. - 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 is0). - 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, return0(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 <= 2000edgeshas exactlyn - 1elements.- Each edge is
[u, v, w]where0 <= u, v <= n - 1and-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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
For a fixed root r, the best root-to-leaf path sum equals the maximum over all leaves L of the sum of edge weights on the path r → L. This can be computed in O(n) with a single DFS. Naively trying all n roots gives O(n²).
To get O(n) overall we use rerooting DP (also called "re-rooting" or "all-roots DP"):
-
Phase 1 — Downward DP: Root the tree at node 0. Compute
down[v]= best sum of a path fromvgoing down intov's subtree to a leaf. Leaves havedown[v] = 0. Internal nodes:down[v] = max over children c of (w(v,c) + down[c]). -
Phase 2 — Upward DP (rerooting): Compute
up[v]= best path sum fromvgoing upward through its parent toward a leaf on that side. Process nodes top-down:- For each child
cofvwith edge weightwc:up[c] = wc + best_alternative_from_v best_alternative_from_vis the maximum among (a)up[v](continue ascending) and (b) the bestdownvalue amongv's other children (go down a sibling branch).- If
vhas no alternatives at all,vitself becomes the leaf, contributing 0.
- For each child
-
Answer: When we treat
vas root, the best leaf path ismax(all child directions, up[v]). We take the global maximum over allv.
Why It Is Correct
Every root-to-leaf path in the tree, when we reroot at one endpoint, is captured by either a "down" direction or the "up" direction from that endpoint. The rerooting propagation correctly accumulates the best alternative going upward by combining up[parent] with the best sibling subtree.
Complexity
- Time: O(n) — two linear passes over the tree.
- Space: O(n) — adjacency list,
down,up, parent arrays.
Reference Solution
from typing import List
def max_path_bonus(n: int, edges: List[List[int]]) -> int:
if n == 1:
return 0
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
parent = [-1] * n
parent_w = [0] * n
order = []
visited = [False] * n
stack = [0]
visited[0] = True
while stack:
v = stack.pop()
order.append(v)
for nb, w in adj[v]:
if not visited[nb]:
visited[nb] = True
parent[nb] = v
parent_w[nb] = w
stack.append(nb)
down = [0] * n
for v in reversed(order):
children_vals = []
for nb, w in adj[v]:
if nb != parent[v]:
children_vals.append(w + down[nb])
if children_vals:
down[v] = max(children_vals)
NEG_INF = float('-inf')
up = [NEG_INF] * n
ans = NEG_INF
for v in order:
children = []
for nb, w in adj[v]:
if nb != parent[v]:
children.append((nb, w, w + down[nb]))
all_directions = [val for (_, _, val) in children]
if up[v] != NEG_INF:
all_directions.append(up[v])
if all_directions:
ans = max(ans, max(all_directions))
child_vals = [val for (_, _, val) in children]
if len(child_vals) == 0:
best1, best2 = NEG_INF, NEG_INF
elif len(child_vals) == 1:
best1, best2 = child_vals[0], NEG_INF
else:
sorted_vals = sorted(child_vals, reverse=True)
best1, best2 = sorted_vals[0], sorted_vals[1]
for (c, wc, vc) in children:
best_sibling = best2 if vc == best1 else best1
alternatives = []
if up[v] != NEG_INF:
alternatives.append(up[v])
if best_sibling != NEG_INF:
alternatives.append(best_sibling)
if alternatives:
up[c] = wc + max(alternatives)
else:
up[c] = wc + 0
return int(ans)