Choose Edges to Maximize Score in a Tree

We traverse a tree, and, for a node j, track and return best result with_j (when we pick an edge coming out of j) and without_j (no edge coming out of j).

That way, for a parent node i, we can find the best edge [i, j] to take (maximize weight + without_j), and best score if we do not take any edge.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from typing import List, Tuple

class Solution:
    def dfs(self, i: int, al: List[List[Tuple[int, int]]]) -> Tuple[int, int]:
        best_i = 0
        without_i = 0
        for j, w in al[i]:
            with_j, without_j = self.dfs(j, al)
            best_i = max(best_i, max(0, w) + without_j - with_j)
            without_i += max(with_j, without_j)
        return best_i + without_i, without_i

    def maxScore(self, edges: List[List[int]]) -> int:
        al = [[] for _ in range(len(edges))]
        for i in range(1, len(edges)):
            al[edges[i][0]].append((i, edges[i][1]))
        with_0, without_0 = self.dfs(0, al)
        return max(with_0, without_0)