KatInterview

Maximum Independent Set Weight on a Tree

Trees & GraphsAuto-graded · 15 test cases
MediumAuto-gradedTrees & Graphstreesdynamic programminggraph traversal

Last 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 of n integers where weights[i] is the weight of node i. 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 exactly n-1 edges for n nodes.

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 at v, including v
  • dp[v][0] = best weight of an independent set in the subtree rooted at v, excluding v

Transitions:

  • If v is included, none of its children may be included:
    dp[v][1] = weights[v] + sum(dp[c][0] for c in children(v))
  • If v is 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] ≤ 1000
  • edges forms a valid tree (connected, acyclic, exactly n-1 edges)
  • If n = 1, edges is empty; the answer is max(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.