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^9
  • 0 <= len(edges) <= max(0, len(values) - 1)
  • Every [u, v] in edges satisfies 0 <= u, v < len(values) with u != v, and the undirected graph is guaranteed to be acyclic (a tree or forest).

Step-by-step walkthrough

  1. Understand the rules, negative values, and forests

    We are given n nodes with integer values[0 .. n - 1] (positive, zero, or negative) and a list of edges. 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:

    1. Edges are undirected: Whether an edge is written [0, 1] or [1, 0], nodes 0 and 1 cannot both be chosen, and any node can serve as a component's root.
    2. Choosing nothing is allowed: The empty subset has sum 0, so negative nodes never force the answer below 0.
    3. 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
    
  2. Why brute force, greedy, and alternating levels all fail

    Testing all 2^n subsets takes over a trillion operations by n = 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.

  3. Key idea: track two DP values per subtree

    Pick any root for a tree so every edge points from a parent down to a child. Inside node v's subtree, the rest of the tree only cares about one yes/no question: was v itself chosen?

    So we compute two numbers for every node v: - take[v]: best valid sum in v's subtree when v IS chosen. - skip[v]: best valid sum in v's subtree when v IS 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 adds max(take[child], skip[child]) >= skip[child] >= 0. So skip[v] is never negative — if values[v] is -4, skip[v] cleanly leaves v out while still keeping any positive grandchildren below v!

  4. 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 with u), 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 start over 0 .. n - 1 and run an explicit stack from each unvisited node:

    • Every unvisited start discovers one connected tree and appends start to roots.
    • Whenever node is popped from stack, we append node to preorder before popping any of its unvisited neighbors (its children). That guarantees every parent appears in preorder earlier 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
    
  5. Compute bottom-up subtree sums in reverse preorder

    Because every parent sits before its children in preorder, walking reversed(preorder) visits every child before its parent (a bottom-up postorder pass).

    We initialize take = list(values) and skip = [0] * num_nodes. When we reach node in reversed(preorder), all of node's children have already folded their contributions into take[node] and skip[node], so node is completely final and ready to fold into parent[node]. Finally, because disconnected trees share no edges, we sum max(take[root], skip[root]) over all 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
    
  6. Trace Example 3 across both trees

    Let's trace values = [9, -4, 8, -6, 11] and edges = [[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) = 28
    
  7. Complete 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), where n = len(values) is the number of nodes: a forest (a collection of disconnected trees) on n nodes contains at most n - 1 edges, so building the adjacency list (per-node lists of neighbors) inspects at most n - 1 edges, the iterative depth-first search (DFS) pushes and pops each node once, and the reverse bottom-up pass performs O(1) arithmetic per node.
  • Space — O(n): neighbors stores 2 * len(edges) <= 2n integers, and parent, visited, preorder, roots, stack, take, and skip each hold at most n entries.

Edge cases

  • Empty graph (values = [], edges = []): roots is empty, so total_sum returns 0.
  • Single node ([5] or [-3]): Returns max(5, 0) = 5 for positive and max(-3, 0) = 0 for negative (choosing the empty subset).
  • All negative values ([-1, -2, -3]): Every skip stays 0, so the empty subset wins with 0.
  • Zero-valued nodes ([0, 5, 5] on a star centered at 0): Picking 0 blocks both 5s (take[0] = 0), whereas skipping 0 takes both leaves (skip[0] = 10).
  • Disconnected forest and isolated nodes: Every unvisited node in 0 .. n - 1 starts 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 stack avoids 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 (13 vs 9).
  • Greedy largest-first selection: Fails whenever smaller neighbors together outweigh one larger node connected to them (8 vs 4 + 5 + 3 = 12).
  • Assuming edges are directed [parent, child] or that node 0 reaches 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 -1 instead of 0 when choosing nothing is valid.
  • Writing skip[p] += take[c] instead of max(take[c], skip[c]): When p is skipped, its child c is allowed to be chosen, not required to be chosen!
  • Using plain recursive DFS in Python: Crashes with RecursionError on 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 start from 0 to n - 1 alongside a visited boolean array: whenever not visited[start], start belongs to an unvisited component, so append start to roots and 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 single O(n) pass. Because separate trees share zero edges, selections in one tree never restrict another, so the global maximum is simply the sum of max(take[root], skip[root]) over all roots.
  • How would you reconstruct the exact set of selected node indices rather than only returning the sum? After filling take and skip bottom-up, walk preorder forward (parents before children) with a chosen = [False] * n array. For each node, if parent[node] != -1 and chosen[parent[node]] is True, keep chosen[node] = False; otherwise set chosen[node] = (take[node] > skip[node]). Collecting all indices with chosen[i] == True runs in O(n) time and yields a valid independent set summing to total_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 forcing u skipped (take[u] = -infinity) and once forcing v skipped (take[v] = -infinity), taking the larger result in O(n) time.

Follow-up questions

Similar questions

More ZipHQ interview questions

All 9 ZipHQ questions →