Maximum Independent Node Sum Across Trees
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given n nodes labeled 0 through n - 1, where node i carries an integer score values[i] (which may be negative, zero, or positive), together with a list edges of undirected pairs [u, v]. The graph contains no cycles: it forms either a single tree or a forest of disconnected trees (including isolated nodes with zero incident edges, or an empty graph when n = 0).
Choose a subset of nodes (possibly empty, which has total score 0) so that no two chosen nodes share an edge in edges, and return the largest total score achievable. Notice that pairs [u, v] in edges have no fixed parent-to-child orientation.
Examples
Example 1
Input:
values = [8, 4, 5, 3]
edges = [[0, 1], [0, 2], [0, 3]]
Output: 12
Node 0 (score 8) is directly linked to nodes 1, 2, and 3 (scores 4, 5, and 3). Picking node 0 forbids all three neighbors and scores 8, whereas leaving node 0 out lets us take {1, 2, 3} for 4 + 5 + 3 = 12.
Example 2
Input:
values = [6, 2, 1, 7]
edges = [[0, 1], [1, 2], [2, 3]]
Output: 13
Nodes form the path 0 — 1 — 2 — 3. Skipping both interior nodes 1 and 2 allows choosing endpoints {0, 3} for 6 + 7 = 13, which beats {0, 2} (7) and {1, 3} (9).
Example 3
Input:
values = [9, -4, 8, -6, 11]
edges = [[1, 0], [1, 2], [4, 3]]
Output: 28
The input consists of two disconnected components: path 0 — 1 — 2 with scores [9, -4, 8] (optimal choice {0, 2} scores 9 + 8 = 17) and edge 3 — 4 with scores [-6, 11] (optimal choice {4} scores 11). Adding both independent components gives 17 + 11 = 28.
Constraints
0 <= len(values) <= 100,000-10^9 <= values[i] <= 10^90 <= len(edges) <= max(0, len(values) - 1)- Every
[u, v]inedgessatisfies0 <= u, v < len(values)withu != v, and the undirected graph is guaranteed to be acyclic (a tree or forest).
Step-by-step walkthrough
Understand the rules, negative values, and forests
We are given
nnodes with integervalues[0 .. n - 1](positive, zero, or negative) and a list ofedges. We want to pick a subset of nodes with the largest total sum such that no two connected nodes are both picked — known in graph theory as a maximum-weight independent set (a set of nodes with no edge between any two of them).Three important details shape our design:
- Edges are undirected: Whether an edge is written
[0, 1]or[1, 0], nodes0and1cannot both be chosen, and any node can serve as a component's root. - Choosing nothing is allowed: The empty subset has sum
0, so negative nodes never force the answer below0. - The input can be a forest: A forest is a collection of one or more disconnected trees (including isolated nodes with no edges). Look at Example 3:
values = [9, -4, 8, -6, 11] edges = [[1, 0], [1, 2], [4, 3]] Tree A: 0 (9) — 1 (-4) — 2 (8) Best pick: {0, 2} -> 9 + 8 = 17 Tree B: 3 (-6) — 4 (11) Best pick: {4} -> 11 Total across forest = 17 + 11 = 28- Edges are undirected: Whether an edge is written
Why brute force, greedy, and alternating levels all fail
Testing all
2^nsubsets takes over a trillion operations byn = 40. Two tempting shortcuts also break on tiny 4-node graphs:Counterexample 1 — Greedy ("pick largest value first", Example 1): 0 (8) / | \ 1(4) 2(5) 3(3) Greedy picks 8, blocking all three leaves -> sum = 8 Optimal skips 8 and picks {1, 2, 3} -> sum = 4 + 5 + 3 = 12 Counterexample 2 — Alternating levels ("even depths vs odd depths", Example 2): 6 — 2 — 1 — 7 Even depths {0, 2}: 6 + 1 = 7 Odd depths {1, 3}: 2 + 7 = 9 Optimal {0, 3}: 6 + 7 = 13 (skips two adjacent middle nodes!)Whether picking a node is worth blocking its neighbors depends on the best totals achievable inside those subtrees. That structure calls for dynamic programming (DP) — solving small subproblems once and combining their saved answers.
Key idea: track two DP values per subtree
Pick any root for a tree so every edge points from a
parentdown to achild. Inside nodev's subtree, the rest of the tree only cares about one yes/no question: wasvitself chosen?So we compute two numbers for every node
v: -take[v]: best valid sum inv's subtree whenvIS chosen. -skip[v]: best valid sum inv's subtree whenvIS NOT chosen.v / \ c1 c2 If v IS chosen (take[v]): - Start with values[v]. - Neither c1 nor c2 can be chosen -> add skip[c1] + skip[c2]. If v IS NOT chosen (skip[v]): - Start with 0. - Each child ci is free to be chosen OR skipped -> add max(take[ci], skip[ci]).Why does this handle negative values automatically? Every leaf starts with
skip[leaf] = 0, and every parent addsmax(take[child], skip[child]) >= skip[child] >= 0. Soskip[v]is never negative — ifvalues[v]is-4,skip[v]cleanly leavesvout while still keeping any positive grandchildren belowv!Build undirected neighbors and root every tree iteratively
To apply the subtree formulas, we first build an adjacency list (
neighbors[u]= all nodes sharing an edge withu), then orient every connected component from a root using depth-first search (DFS) — a traversal that explores along each branch using a stack.Writing recursive DFS would hit Python's ~1,000 call-stack limit on a 100,000-node chain. Instead, we loop
startover0 .. n - 1and run an explicitstackfrom each unvisited node:- Every unvisited
startdiscovers one connected tree and appendsstarttoroots. - Whenever
nodeis popped fromstack, we appendnodetopreorderbefore popping any of its unvisited neighbors (its children). That guarantees every parent appears inpreorderearlier than all of its descendants!
def build_adjacency(num_nodes: int, edges: List[List[int]]) -> List[List[int]]: """Build undirected neighbor lists because edge pairs have no fixed parent->child order.""" # neighbors[u]: list of all nodes directly connected to u, e.g. [[1, 2], [0], [0]]. neighbors = [[] for _ in range(num_nodes)] for u, v in edges: neighbors[u].append(v) neighbors[v].append(u) return neighbors def root_forest(neighbors: List[List[int]]) -> Tuple[List[int], List[int], List[int]]: """Root every connected tree iteratively and return (preorder, parent, roots).""" num_nodes = len(neighbors) # parent[v]: parent of v in its rooted tree, or -1 if v is a component root. parent = [-1] * num_nodes visited = [False] * num_nodes # preorder: every parent appears before all of its descendants, e.g. [0, 1, 2, 3, 4]. preorder = [] # roots: one starting root ID per connected component (handles disconnected forests). roots = [] # Loop over all nodes so disconnected trees and isolated nodes each get rooted. for start in range(num_nodes): if visited[start]: continue visited[start] = True roots.append(start) # Explicit DFS stack avoids Python's ~1,000 recursion limit on deep path trees. stack = [start] while stack: node = stack.pop() preorder.append(node) for neighbor in neighbors[node]: if not visited[neighbor]: visited[neighbor] = True parent[neighbor] = node stack.append(neighbor) return preorder, parent, roots- Every unvisited
Compute bottom-up subtree sums in reverse preorder
Because every parent sits before its children in
preorder, walkingreversed(preorder)visits every child before its parent (a bottom-up postorder pass).We initialize
take = list(values)andskip = [0] * num_nodes. When we reachnodeinreversed(preorder), all ofnode's children have already folded their contributions intotake[node]andskip[node], sonodeis completely final and ready to fold intoparent[node]. Finally, because disconnected trees share no edges, we summax(take[root], skip[root])over allroots.def max_non_adjacent_tree_sum(values: List[int], edges: List[List[int]]) -> int: # Phase 1: Build undirected graph and orient each connected tree from a root. num_nodes = len(values) neighbors = build_adjacency(num_nodes, edges) preorder, parent, roots = root_forest(neighbors) # Phase 2: Initialize subtree DP tables. # take[v]: maximum valid sum in v's subtree when v IS chosen (includes values[v]). # skip[v]: maximum valid sum in v's subtree when v IS NOT chosen (starts at 0). take = list(values) skip = [0] * num_nodes # Phase 3: Walk preorder in reverse so every child finishes before its parent. for node in reversed(preorder): parent_node = parent[node] if parent_node != -1: # If parent_node is chosen, this child cannot be chosen -> add skip[node]. take[parent_node] += skip[node] # If parent_node is skipped, this child may be chosen or skipped -> take best. skip[parent_node] += max(take[node], skip[node]) # Phase 4: Disconnected trees share no edges, so add each component's best root choice. # Because skip[root] >= 0, all-negative components naturally contribute 0 (empty choice). total_sum = 0 for root in roots: total_sum += max(take[root], skip[root]) return total_sumTrace Example 3 across both trees
Let's trace
values = [9, -4, 8, -6, 11]andedges = [[1, 0], [1, 2], [4, 3]]:1. root_forest: - start = 0 discovers Tree A: 0 -> 1 -> 2 - start = 3 discovers Tree B: 3 -> 4 roots = [0, 3] parent = [-1, 0, 1, -1, 3] preorder = [0, 1, 2, 3, 4] 2. Initial tables: take = [9, -4, 8, -6, 11] skip = [0, 0, 0, 0, 0] 3. Walk reversed(preorder) = [4, 3, 2, 1, 0]: - node 4 (take = 11, skip = 0), parent = 3: take[3] += skip[4] (0) -> take[3] = -6 skip[3] += max(11, 0) (11) -> skip[3] = 11 - node 3 (take = -6, skip = 11), parent = -1 (root of Tree B) - node 2 (take = 8, skip = 0), parent = 1: take[1] += skip[2] (0) -> take[1] = -4 skip[1] += max(8, 0) (8) -> skip[1] = 8 - node 1 (take = -4, skip = 8), parent = 0: take[0] += skip[1] (8) -> take[0] = 9 + 8 = 17 skip[0] += max(-4, 8) (8) -> skip[0] = 8 - node 0 (take = 17, skip = 8), parent = -1 (root of Tree A) 4. Sum over roots [0, 3]: max(take[0], skip[0]) + max(take[3], skip[3]) = max(17, 8) + max(-6, 11) = 28Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def build_adjacency(num_nodes: int, edges: List[List[int]]) -> List[List[int]]: """Build undirected neighbor lists because edge pairs have no fixed parent->child order.""" # neighbors[u]: list of all nodes directly connected to u, e.g. [[1, 2], [0], [0]]. neighbors = [[] for _ in range(num_nodes)] for u, v in edges: neighbors[u].append(v) neighbors[v].append(u) return neighbors def root_forest(neighbors: List[List[int]]) -> Tuple[List[int], List[int], List[int]]: """Root every connected tree iteratively and return (preorder, parent, roots).""" num_nodes = len(neighbors) # parent[v]: parent of v in its rooted tree, or -1 if v is a component root. parent = [-1] * num_nodes visited = [False] * num_nodes # preorder: every parent appears before all of its descendants, e.g. [0, 1, 2, 3, 4]. preorder = [] # roots: one starting root ID per connected component (handles disconnected forests). roots = [] # Loop over all nodes so disconnected trees and isolated nodes each get rooted. for start in range(num_nodes): if visited[start]: continue visited[start] = True roots.append(start) # Explicit DFS stack avoids Python's ~1,000 recursion limit on deep path trees. stack = [start] while stack: node = stack.pop() preorder.append(node) for neighbor in neighbors[node]: if not visited[neighbor]: visited[neighbor] = True parent[neighbor] = node stack.append(neighbor) return preorder, parent, roots def max_non_adjacent_tree_sum(values: List[int], edges: List[List[int]]) -> int: # Phase 1: Build undirected graph and orient each connected tree from a root. num_nodes = len(values) neighbors = build_adjacency(num_nodes, edges) preorder, parent, roots = root_forest(neighbors) # Phase 2: Initialize subtree DP tables. # take[v]: maximum valid sum in v's subtree when v IS chosen (includes values[v]). # skip[v]: maximum valid sum in v's subtree when v IS NOT chosen (starts at 0). take = list(values) skip = [0] * num_nodes # Phase 3: Walk preorder in reverse so every child finishes before its parent. for node in reversed(preorder): parent_node = parent[node] if parent_node != -1: # If parent_node is chosen, this child cannot be chosen -> add skip[node]. take[parent_node] += skip[node] # If parent_node is skipped, this child may be chosen or skipped -> take best. skip[parent_node] += max(take[node], skip[node]) # Phase 4: Disconnected trees share no edges, so add each component's best root choice. # Because skip[root] >= 0, all-negative components naturally contribute 0 (empty choice). total_sum = 0 for root in roots: total_sum += max(take[root], skip[root]) return total_sum✅ Submit now — all tests should pass.
Intuition & how it works
Imagine inviting people from an org chart to a dinner party where each guest brings a score (values[i]), with one rule: if you invite a manager, none of their direct reports may attend (forming an independent set — a subset of nodes where no two share an edge). At any person v, the rest of the hierarchy above v only cares whether v attends or stays home. That lets us use dynamic programming (DP) — solving smaller subtrees once and combining their saved answers — by storing just two numbers per node: take[v] (best score in v's subtree when v attends, meaning every direct child stays home) and skip[v] (best score in v's subtree when v stays home, meaning each child independently picks the better of attending or staying home).
Simple shortcuts all fail here. Checking every subset takes 2^n work, exceeding a trillion checks by n = 40. Greedily choosing the largest value fails on Example 1 (8 connected to 4, 5, 3: picking 8 blocks all three leaves instead of scoring 4 + 5 + 3 = 12), and picking every other tree level fails on Example 2 (6 — 2 — 1 — 7: even or odd levels give 7 or 9, whereas skipping two middle nodes gives 6 + 7 = 13).
Let's walk through the first component of Example 3 (0 — 1 — 2 with values = [9, -4, 8], rooted at 0):
1. Leaf 2 (value = 8): Has no children, so take[2] = 8 and skip[2] = 0.
2. Middle node 1 (value = -4): If chosen, child 2 must be skipped (take[1] = -4 + 0 = -4); if skipped, child 2 takes its best option (skip[1] = max(8, 0) = 8).
3. Root 0 (value = 9): If chosen, child 1 must be skipped (take[0] = 9 + skip[1] = 9 + 8 = 17); if skipped, child 1 takes its best option (skip[0] = max(-4, 8) = 8).
4. Component choice: max(take[0], skip[0]) = max(17, 8) = 17 (choosing nodes 0 and 2), which adds to component {3, 4}'s 11 for 28.
Complexity
- Time —
O(n), wheren = len(values)is the number of nodes: a forest (a collection of disconnected trees) onnnodes contains at mostn - 1edges, so building the adjacency list (per-node lists of neighbors) inspects at mostn - 1edges, the iterative depth-first search (DFS) pushes and pops each node once, and the reverse bottom-up pass performsO(1)arithmetic per node. - Space —
O(n):neighborsstores2 * len(edges) <= 2nintegers, andparent,visited,preorder,roots,stack,take, andskipeach hold at mostnentries.
Edge cases
- Empty graph (
values = [],edges = []):rootsis empty, sototal_sumreturns0. - Single node (
[5]or[-3]): Returnsmax(5, 0) = 5for positive andmax(-3, 0) = 0for negative (choosing the empty subset). - All negative values (
[-1, -2, -3]): Everyskipstays0, so the empty subset wins with0. - Zero-valued nodes (
[0, 5, 5]on a star centered at0): Picking0blocks both5s (take[0] = 0), whereas skipping0takes both leaves (skip[0] = 10). - Disconnected forest and isolated nodes: Every unvisited node in
0 .. n - 1starts its own component root, and independent component sums add together. - Arbitrary edge directions and root labels: Treating edges as undirected ensures
[child, parent]and[parent, child]behave identically. - 100,000-node skewed path: The explicit
stackavoids Python's ~1,000-frame recursion limit.
Common mistakes
- Taking the max of all-even vs all-odd depths: Misses optimal solutions that skip two consecutive levels, such as
6 — 2 — 1 — 7(13vs9). - Greedy largest-first selection: Fails whenever smaller neighbors together outweigh one larger node connected to them (
8vs4 + 5 + 3 = 12). - Assuming edges are directed
[parent, child]or that node0reaches everything: Fails when an edge is listed[child, parent](as in[[1, 0], [4, 3]]) or when the graph has multiple components. - Forcing at least one node on all-negative inputs: Returning
-1instead of0when choosing nothing is valid. - Writing
skip[p] += take[c]instead ofmax(take[c], skip[c]): Whenpis skipped, its childcis allowed to be chosen, not required to be chosen! - Using plain recursive DFS in Python: Crashes with
RecursionErroron deep trees (n = 100,000).
Alternative approaches
- Recursive postorder DFS returning
(take, skip): A postorder traversal visits all children recursively before computing the parent's result. It expresses the exact same recurrence in ~12 lines and works well when tree height is guaranteed small or in languages with large call stacks. - Breadth-first search (BFS) level order reversed: Using a queue to list nodes level by level also places every parent before its children, so reversing a BFS order works identically to reversing
preorder.
Follow-up questions
- How can you partition disconnected trees and combine their optimal totals? Sweep an index
startfrom0ton - 1alongside avisitedboolean array: whenevernot visited[start],startbelongs to an unvisited component, so appendstarttorootsand run an iterative DFS (or BFS) to orient that tree. Union-find — a disjoint-set data structure that tracks connected components under edge merges — can also identify components, though DFS discovers components and records parent-before-child ordering in a singleO(n)pass. Because separate trees share zero edges, selections in one tree never restrict another, so the global maximum is simply the sum ofmax(take[root], skip[root])over allroots. - How would you reconstruct the exact set of selected node indices rather than only returning the sum? After filling
takeandskipbottom-up, walkpreorderforward (parents before children) with achosen = [False] * narray. For eachnode, ifparent[node] != -1andchosen[parent[node]]isTrue, keepchosen[node] = False; otherwise setchosen[node] = (take[node] > skip[node]). Collecting all indices withchosen[i] == Trueruns inO(n)time and yields a valid independent set summing tototal_sum. - Why does this dynamic programming approach break if the graph contains cycles, and how can a single cycle be handled? On a general graph with arbitrary cycles, finding a maximum-weight independent set is NP-hard — a class of problems with no known polynomial-time algorithm — because choices propagate around cycles and constrain ancestors that have already been decided. When a component contains just one cycle (a unicyclic graph, like circular "House Robber II"), locate one cycle edge
(u, v), remove it to leave a tree, and run tree DP twice: once forcinguskipped (take[u] = -infinity) and once forcingvskipped (take[v] = -infinity), taking the larger result inO(n)time.
Follow-up questions
- How can you partition disconnected trees and combine their optimal totals?
- How would you reconstruct the exact set of selected node indices rather than only returning the sum?
- Why does this dynamic programming approach break if the graph contains cycles, and how can a single cycle be handled?
Similar questions
- Suited Runs and Same-Rank Card Groups
- Forest Root IDs and Root-to-Target Path
- Worst-Case Pursuit Time on an Undirected Graph
- Optimal Independent Node Sum on N-ary Trees
- In-Memory Key-Field Store with Record Expiry and Time Travel
- Conditional Form Evaluator with Numeric and Boolean Rules
More ZipHQ interview questions
- Conditional Form Evaluator with Numeric and Boolean Rules Medium
- Worst-Case Pursuit Time on an Undirected Graph Hard
- Optimal Independent Node Sum on N-ary Trees Medium Pro
- In-Memory Key-Field Store with Record Expiry and Time Travel Hard Pro
- Debugging a Java LinkedHashMap LRU Cache Medium Pro
- Suited Runs and Same-Rank Card Groups Medium Pro
- Forest Root IDs and Root-to-Target Path Medium Pro
- Caching Repeated Approval Alerts with Safe Severity Updates Hard Pro