Leetcode #2378: Choose Edges to Maximize Score in a Tree
In this guide, we solve Leetcode #2378 Choose Edges to Maximize Score in a Tree in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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] = [pari, weighti] indicates that node pari is the parent of node i, and the edge between them has a weight equal to weighti.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Tree, Depth-First Search, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
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.
Python Solution
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]
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.