KatInterview

Maximum Sum of Independent Nodes in a Tree

Trees & GraphsAuto-graded · 15 test cases
EasyAuto-gradedTrees & Graphstreedynamic programmingrecursion

Last updated

Tests tree DP by finding the maximum sum of node values when no two selected nodes may be adjacent (parent-child) in a rooted tree.

Maximum Sum of Independent Nodes in a Tree

You are given a rooted tree with n nodes numbered 0 through n - 1. Node 0 is always the root.

The tree is described by a list parent of length n where parent[i] is the parent of node i. For the root, parent[0] == -1. Each node i also has an integer value values[i].

Your task is to select a subset of nodes such that:

  • No two selected nodes are directly connected by an edge (i.e., no selected node is the parent or child of another selected node).
  • The sum of values of the selected nodes is maximised.

Return the maximum possible sum.

How it works

  • Build the tree from the parent array.
  • Use tree DP: for every node decide whether to include it (gaining its value but forbidding its children) or exclude it (allowing each child to make its own best choice).
  • Recurse from the root.

Constraints

  • 1 ≤ n ≤ 2000
  • len(parent) == len(values) == n
  • parent[0] == -1; for all i ≥ 1, 0 ≤ parent[i] < n and parent[i] != i
  • The input is guaranteed to describe a valid rooted tree (no cycles, every non-root node has exactly one parent).
  • -1000 ≤ values[i] ≤ 1000
  • Nodes may have negative values; you are never forced to select any node (an empty selection with sum 0 is always valid).

Examples

Example 1

Input: max_independent_node_sum([-1, 0, 0, 1, 1], [10, 5, 3, 4, 2])

Output: 16

Example 2

Input: max_independent_node_sum([-1, 0, 1, 2], [3, 7, 4, 5])

Output: 12

Example 3

Input: max_independent_node_sum([-1], [42])

Output: 42

Hints

Hint 1

Define dp(node) returning a pair (include_sum, exclude_sum): the best sum when this node is included vs. excluded.

Hint 2

When a node is included its value is added and all children must be excluded. When it is excluded each child independently picks the better of its own include/exclude.

Hint 3

Because all values can be negative, make sure to allow the empty selection — the answer is max(include_sum, exclude_sum) at the root, and each subproblem naturally handles this since negative contributions are never forced.