Maximum Independent Set on Line and Binary Tree
Dynamic ProgrammingAuto-graded · 25 test casesLast 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
- Linear Chain (
v): A list of non-negative integers representing the node values in sequence from index0tolen(v) - 1. - Binary Tree (
tree): A list of nodes where index0is 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. Iftreeis empty ([]), the tree topology contains zero nodes.
Output
Return a list of two integers: [linear_max, tree_max].
Constraints
0 <= len(v) <= 10^50 <= len(tree) <= 10^4- Node values are integers between
0and10^4. - For
tree, index0is always the root unlesstreeis empty. - Tree child pointers refer to valid indices within
treeor-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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach Walkthrough
Both variants can be solved using dynamic programming by breaking down the decision at each node into two mutually exclusive choices: include the current node or exclude it.
Part 1: Linear Chain
For a sequential list of values, iterating from left to right allows us to update two rolling state variables:
include: Max sum up to the current element given that the current element is selected.exclude: Max sum up to the current element given that the current element is omitted.
For each new value x:
- If we select
x, we must omit the immediately preceding element, sonew_include = exclude + x. - If we omit
x, the previous element could either be included or excluded, sonew_exclude = max(include, exclude).
At the end of the chain, the answer is max(include, exclude).
Part 2: Binary Tree
For the tree structure, every node $u$ computes a pair of values (take, skip):
take: $u.\text{value} + \text{skip}{\text{left_child}} + \text{skip}{\text{right_child}}$ (including node $u$ forces us to skip both direct children).skip: $\max(\text{take}{\text{left}}, \text{skip}{\text{left}}) + \max(\text{take}{\text{right}}, \text{skip}{\text{right}})$ (skipping node $u$ leaves both subtrees independently free to choose their optimal state).
Because the state of a parent node depends directly on the calculated states of its child nodes, we must compute these pairs in post-order. To handle potential deep/skewed trees without exceeding Python's call stack limit, an explicit iterative stack using a standard post-order traversal ((node_index, visited) flags) is implemented.
Complexity
- Linear Array: $O(n)$ time complexity, where $n$ is
len(v), requiring $O(1)$ extra memory space. - Binary Tree: $O(m)$ time complexity, where $m$ is
len(tree), requiring $O(m)$ auxiliary space for the explicit stack and state tracking arraydp.
Reference Solution
from typing import List
def solve_two_robbery_variants(v: List[int], tree: List[List[int]]) -> List[int]:
# Part 1: Linear chain dynamic programming
include_val = 0
exclude_val = 0
for val in v:
new_include = exclude_val + val
new_exclude = max(include_val, exclude_val)
include_val, exclude_val = new_include, new_exclude
linear_max = max(include_val, exclude_val)
# Part 2: Tree topology dynamic programming
if not tree:
return [linear_max, 0]
# dp[i] = (max_with_node_i, max_without_node_i)
dp = [(0, 0)] * len(tree)
stack = [(0, False)]
while stack:
node_idx, visited = stack.pop()
if node_idx == -1:
continue
if not visited:
stack.append((node_idx, True))
left_idx = tree[node_idx][1]
right_idx = tree[node_idx][2]
if right_idx != -1:
stack.append((right_idx, False))
if left_idx != -1:
stack.append((left_idx, False))
else:
val, left_idx, right_idx = tree[node_idx]
left_inc, left_exc = dp[left_idx] if left_idx != -1 else (0, 0)
right_inc, right_exc = dp[right_idx] if right_idx != -1 else (0, 0)
take = val + left_exc + right_exc
skip = max(left_inc, left_exc) + max(right_inc, right_exc)
dp[node_idx] = (take, skip)
tree_max = max(dp[0])
return [linear_max, tree_max]