Maximum Independent Set Weight on a Tree
Trees & GraphsAuto-graded · 15 test casesLast updated
Tests tree DP by computing the maximum total weight of a node subset where no two chosen nodes share an edge (weighted tree independent set).
Maximum Independent Set Weight on a Tree
You are given a weighted tree with n nodes numbered 0 through n-1. An independent set is a subset of nodes such that no two nodes in the subset are directly connected by an edge.
Your task is to find the maximum total weight achievable by any independent set of nodes (including the empty set, which has weight 0).
The tree is provided as a list of edges and a list of node weights.
Input
weights: a list ofnintegers whereweights[i]is the weight of nodei. Weights may be negative.edges: a list of pairs[u, v](each a two-element list of ints) representing the undirected edges of the tree. There are exactlyn-1edges fornnodes.
Output
Return a single integer: the maximum sum of weights over all independent sets.
How it works
Root the tree at node 0. For each node define:
dp[v][1]= best weight of an independent set in the subtree rooted atv, includingvdp[v][0]= best weight of an independent set in the subtree rooted atv, excludingv
Transitions:
- If
vis included, none of its children may be included:
dp[v][1] = weights[v] + sum(dp[c][0] for c in children(v)) - If
vis excluded, each child may or may not be included:
dp[v][0] = sum(max(dp[c][0], dp[c][1]) for c in children(v))
The answer is max(dp[0][0], dp[0][1]).
Constraints
1 ≤ n ≤ 2000-1000 ≤ weights[i] ≤ 1000edgesforms a valid tree (connected, acyclic, exactlyn-1edges)- If
n = 1,edgesis empty; the answer ismax(0, weights[0]) - The empty set (weight 0) is always a valid candidate
Examples
Example 1
Input: max_independent_set_weight([3, 5, 2, 4, 1], [[0, 1], [1, 2], [1, 3], [3, 4]])
Output: 9
Example 2
Input: max_independent_set_weight([10, -5, 10], [[0, 1], [1, 2]])
Output: 20
Example 3
Input: max_independent_set_weight([-3], [])
Output: 0
Hints
Hint 1
Root the tree at node 0 and perform a post-order DFS so every subtree is solved before its parent.
Hint 2
At each node keep two values: the best independent-set weight when the node is included versus excluded; the excluded case lets each child freely choose its own best.
Hint 3
Because weights can be negative, remember that the empty set (total weight 0) is always valid — take the maximum of your root DP values and 0.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
A tree has no cycles, so we can root it at any node (we pick node 0) and solve the problem bottom-up with tree DP. At each node we track two scenarios:
- Include the node: add its weight, but none of its children can be included.
- Exclude the node: each child independently chooses whichever option (include or exclude) gives it the higher contribution.
DP Definition
For each node v:
dp[v][0]= maximum independent-set weight in the subtree rooted atv, withvnot selected.dp[v][1]= maximum independent-set weight in the subtree rooted atv, withvselected.
Transitions
For each child c of v:
dp[v][1] += dp[c][0] # v taken → c must be skipped
dp[v][0] += max(dp[c][0], dp[c][1]) # v skipped → c takes its best
Base case (leaf node): dp[v][1] = weights[v], dp[v][0] = 0.
Answer
max(0, dp[0][0], dp[0][1])
The 0 accounts for the empty set being valid when all weights are negative.
Correctness
By induction on subtree depth: a leaf's DP values are trivially correct. For an internal node, assuming all children's DP values are correct, the transitions correctly combine them because the independence constraint only crosses parent-child edges (the tree structure ensures no other edges exist between subtrees).
Implementation
We use an iterative DFS to avoid Python recursion limits on large trees, collecting nodes in DFS-visit order, then processing them in reverse (post-order: children before parents).
Complexity
- Time: O(n) — each node and edge is visited once.
- Space: O(n) — adjacency list, DP table, and DFS stack/order array.
Reference Solution
from typing import List
def max_independent_set_weight(weights: List[int], edges: List[List[int]]) -> int:
n = len(weights)
if n == 0:
return 0
# Build adjacency list
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
# dp[v] = [best_excluding_v, best_including_v]
dp = [[0, 0] for _ in range(n)]
for i in range(n):
dp[i][1] = weights[i]
parent = [-1] * n
order = []
visited = [False] * n
stack = [0]
visited[0] = True
while stack:
v = stack.pop()
order.append(v)
for nb in adj[v]:
if not visited[nb]:
visited[nb] = True
parent[nb] = v
stack.append(nb)
# Process in reverse order (post-order: children before parents)
for v in reversed(order):
for c in adj[v]:
if parent[c] == v: # c is a child of v
dp[v][1] += dp[c][0]
dp[v][0] += max(dp[c][0], dp[c][1])
return max(0, dp[0][0], dp[0][1])