Choose Edges to Maximize Score in a Tree Problem
Description
LeetCode Problem 2378.
You are given a weighted tree consisting of n nodes numbered from 0 to n - 1.
The tree is rooted at node 0 and represented with a 2D array edges of size n where edges[i] = [par_i, weight_i] indicates that node par_i is the parent of node i, and the edge between them has a weight equal to weight_i. Since the root does not have a parent, you have edges[0] = [-1, -1].
Choose some edges from the tree such that no two chosen edges are adjacent and the sum of the weights of the chosen edges is maximized.
Return the maximum sum of the chosen edges.
Note:
- You are allowed to not choose any edges in the tree, the sum of weights in this case will be
0. - Two edges
Edge_1andEdge_2in the tree are adjacent if they have a common node.- In other words, they are adjacent if
Edge_1connects nodesaandbandEdge_2connects nodesbandc.
- In other words, they are adjacent if
Example 1:

Input: edges = [[-1,-1],[0,5],[0,10],[2,6],[2,4]]
Output: 11
Explanation: The above diagram shows the edges that we have to choose colored in red.
The total score is 5 + 6 = 11.
It can be shown that no better score can be obtained.
Example 2:

Input: edges = [[-1,-1],[0,5],[0,-6],[0,7]]
Output: 7
Explanation: We choose the edge with weight 7.
Note that we cannot choose more than one edge because all edges are adjacent to each other.
Constraints:
n == edges.length1 <= n <= 10^5edges[i].length == 2par_0 == weight_0 == -10 <= par_i <= n - 1for alli >= 1.par_i != i-10^6 <= weight_i <= 10^6for alli >= 1.edgesrepresents a valid tree.
Solution
Approach: Tree DP
Root the tree at node 0. For each node i, compute two values from its subtree: a, the best score when no edge from i to a child is taken, and b, the best score when at most one child edge is taken (the best overall). A parent that takes the edge to i needs the value a of i.
ais the sum ofbover all children.bstarts froma; then pick the childjwith the largest gaina_j + w - b_j, wherewis the weight of edge(i, j), and add the gain if it is positive.
The answer is b of the root.
Complexity: O(n) time and O(n) space.
from collections import defaultdict
class Solution:
def maxScore(self, edges: List[List[int]]) -> int:
def dfs(i):
a = b = t = 0
for j, w in g[i]:
x, y = dfs(j)
a += y
b += y
t = max(t, x - y + w)
b += t
return a, b
g = defaultdict(list)
for i, (p, w) in enumerate(edges[1:], 1):
g[p].append((i, w))
return dfs(0)[1]