Maximum Subtree Weight for Every Node in a Network
Trees & GraphsAuto-graded · 24 test casesLast updated
Find the maximum sum of a connected component containing each node in an undirected tree using dynamic programming with rerooting.
You are given an undirected tree with $n$ nodes indexed from $0$ to $n - 1$. Each node $i$ has an assigned numerical weight stored in an array weights of size $n$, where each weight is either $1$ or $-1$.
A connected component of the tree is valid for a target node $u$ if it is a non-empty connected subgraph that includes node $u$. The overall score of such a component is defined as the sum of weights[v] for all nodes $v$ belonging to the component.
Determine the maximum possible score of a valid connected component containing node $i$ for every node $i \in [0, n - 1]$.
Return an array of length $n$, where the $i$-th element is the maximum score achievable for node $i$.
Constraints
- $1 \le n \le 10^5$
edgeshas length $n - 1$- Each edge in
edgesis a pair $[u, v]$ with $0 \le u, v < n$ - The graph defined by
edgesis guaranteed to be a connected tree. weights[i]is either $1$ or $-1$ for all $0 \le i < n$.
Examples
Example 1
Input: max_connected_strength(5, [[0, 1], [0, 2], [1, 3], [1, 4]], [1, -1, 1, 1, 1])
Output: [3, 3, 3, 3, 3]
Example 2
Input: max_connected_strength(3, [[0, 1], [1, 2]], [-1, -1, -1])
Output: [-1, -1, -1]
Example 3
Input: max_connected_strength(1, [], [-1])
Output: [-1]
Example 4
Input: max_connected_strength(4, [[0, 1], [1, 2], [2, 3]], [1, 1, 1, 1])
Output: [4, 4, 4, 4]
Hints
Hint 1
If you fix node 0 as the root, can you compute the maximum score of a subtree component rooted at u that extends into u's descendants?
Hint 2
How can you greedily decide whether to attach a child's subtree component to parent node u?
Hint 3
Once the root's total score is computed, how can you re-root the DP to pass down the optimal component score coming from u's parent?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The problem asks for the maximum weight connected component containing each node $i$. An $O(n^2)$ approach would run a tree DP starting from every node independently. However, we can solve this in $O(n)$ time using rerooting dynamic programming (tree DP in two passes).
Step 1: Bottom-up DP (Fixing a root)
Arbitrarily pick node $0$ as the root. Define down[u] as the maximum score of a connected component containing node $u$ that is entirely restricted to $u$'s subtree.
For a node $u$, any attached component in a child $v$'s subtree must include child $v$ itself. Therefore, we can independently choose to include or exclude each child subtree: $$\text{down}[u] = \text{weights}[u] + \sum_{v \in \text{children}(u)} \max(0, \text{down}[v])$$
Step 2: Top-down Rerooting
To compute the overall optimal score ans[v] for all nodes, we must also account for components extending into $v$'s parent side.
Suppose we already know ans[u] for parent node $u$. ans[u] includes the contribution from all neighbor directions of $u$, including $v$'s subtree (which contributed $\max(0, \text{down}[v])$).
To find the best contribution from the rest of the tree excluding $v$'s subtree, we subtract $v$'s subtree contribution from ans[u]:
$$\text{up_contribution} = \text{ans}[u] - \max(0, \text{down}[v])$$
Node $v$ can then incorporate this upper component if it is strictly positive: $$\text{ans}[v] = \text{down}[v] + \max(0, \text{up_contribution})$$
We traverse nodes in topological/BFS order to ensure ans[u] is computed before processing its children $v$.
Complexity
- Time Complexity: $\mathcal{O}(n)$ — One BFS pass to build parent pointers and topological order, one bottom-up pass, and one top-down pass. Each edge is examined a constant number of times.
- Space Complexity: $\mathcal{O}(n)$ — To store the adjacency graph, parents array, topological order, and DP tables.
Python Reference Code
from typing import List
def max_connected_strength(n: int, edges: List[List[int]], weights: List[int]) -> List[int]:
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
# BFS from node 0 to build parent array and top-down ordering
parent = [-1] * n
order = [0]
for u in order:
for v in graph[u]:
if v != parent[u]:
parent[v] = u
order.append(v)
# Bottom-up pass: compute subtree optimal scores
down = weights[:]
for u in reversed(order[1:]):
p = parent[u]
if down[u] > 0:
down[p] += down[u]
# Top-down rerooting pass: compute global optimal scores
ans = down[:]
for u in order:
for v in graph[u]:
if parent[v] == u:
contribution = ans[u] - max(0, down[v])
ans[v] = down[v] + max(0, contribution)
return ans