DP on Trees - Problem
Given a tree (connected acyclic graph) where each node has a positive integer weight, find the maximum weight independent set.
An independent set is a set of nodes where no two nodes are adjacent (directly connected by an edge). Your goal is to select nodes that maximize the total weight while ensuring no two selected nodes share an edge.
The tree is represented as an adjacency list where adj[i] contains all nodes connected to node i. Node weights are given in array weights where weights[i] is the weight of node i.
Input & Output
Example 1 — Linear Tree
$
Input:
adj = [[1],[0,2],[1]], weights = [4,1,2]
›
Output:
6
💡 Note:
Tree structure: 0-1-2 with weights [4,1,2]. Optimal independent set is {0,2} with total weight 4+2=6. Node 1 is adjacent to both 0 and 2, so we can't include it with either.
Example 2 — Star Tree
$
Input:
adj = [[1,2,3],[0],[0],[0]], weights = [1,4,4,4]
›
Output:
12
💡 Note:
Star tree with center 0 (weight=1) connected to leaves 1,2,3 (weights=4 each). Better to exclude center and take all leaves: 4+4+4=12 > 1.
Example 3 — Single Node
$
Input:
adj = [[]], weights = [5]
›
Output:
5
💡 Note:
Tree with single node of weight 5. Only option is to include it, giving maximum weight 5.
Constraints
- 1 ≤ n ≤ 104 where n is number of nodes
- 1 ≤ weights[i] ≤ 104
- The input represents a valid tree (connected and acyclic)
- Nodes are numbered from 0 to n-1
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code