KatInterview

Maximum Subtree Weight for Every Node in a Network

Trees & GraphsAuto-graded · 24 test cases
MediumAuto-gradedTrees & Graphstrees-graphsdynamic-programmingtree-dp

Last 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$
  • edges has length $n - 1$
  • Each edge in edges is a pair $[u, v]$ with $0 \le u, v < n$
  • The graph defined by edges is 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?