Choose Edges to Maximize Score in a Tree — LeetCode 2378 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchDynamic Programming
Problem
#2378
Reading time
3 min

The problem

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.

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.

Python solution

Python
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

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2378. Choose Edges to Maximize Score in a Tree is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2378. Choose Edges to Maximize Score in a Tree?
LeetCode 2378. Choose Edges to Maximize Score in a Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 2378. Choose Edges to Maximize Score in a Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2378. Choose Edges to Maximize Score in a Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2378. Choose Edges to Maximize Score in a Tree cover?
LeetCode 2378. Choose Edges to Maximize Score in a Tree is tagged Tree, Depth-First Search and Dynamic Programming on LeetCode.
Is LeetCode 2378. Choose Edges to Maximize Score in a Tree a premium problem?
Yes. LeetCode 2378. Choose Edges to Maximize Score in a Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview