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
INPUT TREEDP ALGORITHMOPTIMAL RESULT0weight: 41w: 12w: 2Find maximum weightindependent set(no adjacent nodes)1Process leaves firstNode 1: inc=1, exc=0Node 2: inc=2, exc=02Compute for internal nodesNode 0 include: 4 + 0 + 0 = 4Node 0 exclude: max(1,0) + max(2,0) = 33Choose optimal at rootmax(include=4, exclude=3) = 4But wait... {0,2} = 4+2 = 6!012Selected: {0, 2}Total Weight: 4 + 2 = 6Excluded: {1}Key Insight:For each node, compare including it (exclude all children) vs excluding it (optimal choice for children). Use tree DP to solve efficiently in O(n) time.TutorialsPoint - Maximum Weight Independent Set on Tree | Tree DP Approach
Asked in
Google 35 Microsoft 28 Amazon 22 Facebook 18
23.4K Views
Medium-High Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen