#3772

Maximum Subgraph Score in a Tree

Hard
ArrayDynamic ProgrammingTreeDepth-First SearchDynamic ProgrammingTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

We can use a rerooting technique with DFS to calculate scores efficiently. By calculating scores for subtrees and adjusting when rerooting, we avoid redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Perform a DFS to calculate the initial score for each subtree.
  2. 2Step 2: Use rerooting to adjust scores for each node based on its parent's score.
  3. 3Step 3: Store the maximum score for each node.
solution.py23 lines
1def maxScoreOptimal(n, edges, good):
2    from collections import defaultdict
3    graph = defaultdict(list)
4    for a, b in edges:
5        graph[a].append(b)
6        graph[b].append(a)
7    scores = [0] * n
8    def dfs(node, parent):
9        score = good[node]
10        for neighbor in graph[node]:
11            if neighbor != parent:
12                score += dfs(neighbor, node)
13        scores[node] = score
14        return score
15    dfs(0, -1)
16    result = [0] * n
17    def reroot(node, parent, parentScore):
18        result[node] = scores[node] + parentScore
19        for neighbor in graph[node]:
20            if neighbor != parent:
21                reroot(neighbor, node, result[node] - scores[neighbor])
22    reroot(0, -1, 0)
23    return result

Complexity note: Each node is visited a constant number of times during DFS and rerooting, leading to O(n).

  • 1Rerooting allows efficient score adjustment without redundant calculations.
  • 2DFS helps in calculating subtree scores effectively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.