KatInterview

Maximum Independent Set on Line and Binary Tree

Dynamic ProgrammingAuto-graded · 25 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingtrees-graphsarrays

Last updated

Find the maximum weight independent set for both a linear sequence and a binary tree network under non-adjacency constraints.

You are analyzing optimal placement strategies for network relays under physical interference constraints. You are presented with two distinct topology models: a linear chain and a binary tree structure.

In both topologies, selecting a node grants a total value equal to that node's weight, but selecting two adjacent nodes causes signal interference and is strictly prohibited. Two nodes are adjacent if they are consecutive in the linear chain, or if one is the direct parent of the other in the tree structure.

Write a function that calculates the maximum total value obtainable from valid node selections for both structures and returns the two results as a 2-element list [linear_max, tree_max].

Topology Representation

  1. Linear Chain (v): A list of non-negative integers representing the node values in sequence from index 0 to len(v) - 1.
  2. Binary Tree (tree): A list of nodes where index 0 is the root node. Each element is a list [value, left_child_index, right_child_index]. If a node has no left or right child, the corresponding index is set to -1. If tree is empty ([]), the tree topology contains zero nodes.

Output

Return a list of two integers: [linear_max, tree_max].

Constraints

  • 0 <= len(v) <= 10^5
  • 0 <= len(tree) <= 10^4
  • Node values are integers between 0 and 10^4.
  • For tree, index 0 is always the root unless tree is empty.
  • Tree child pointers refer to valid indices within tree or -1.

Examples

Example 1

Input: solve_two_robbery_variants([2, 7, 9, 3, 1], [[3, 1, 2], [2, -1, -1], [3, -1, -1]])

Output: [12, 5]

Example 2

Input: solve_two_robbery_variants([2], [[3, 1, 2], [2, -1, -1], [3, -1, -1]])

Output: [2, 5]

Example 3

Input: solve_two_robbery_variants([1, 2, 3, 1], [[3, 1, 2], [2, 3, -1], [3, -1, 4], [3, -1, -1], [1, -1, -1]])

Output: [4, 7]

Hints

Hint 1

For the linear chain, keep track of two dynamic programming states at each step: the best sum including the current node, and the best sum excluding it.

Hint 2

For the tree, compute a pair of values `(max_if_selected, max_if_skipped)` for each subtree in post-order traversal.

Hint 3

Because tree depth can reach up to 10^4 in a skewed chain, prefer an explicit stack or iterative post-order traversal to avoid Python recursion depth issues.