Katkat

Solve Two Robbery Optimization Variants

FlexportSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to apply dynamic programming to linear structures and tree-based data structures to find the maximum weight independent set under constraints.

Part 1: The Linear Warehouse

You are tasked with scheduling security patrols in a warehouse consisting of a line of n storage units, where each unit i has a value v[i]. Due to security regulations, you cannot monitor two adjacent storage units. Given an array v of non-negative integers, find the maximum total value you can secure.

Example

v = [2, 7, 9, 3, 1] Result: 12 (Select units 0, 2, and 4: 2 + 9 + 1 = 12)

Part 2: The Hierarchical Warehouse

Now consider a warehouse structured like a binary tree, where each node is a storage unit. If you monitor a unit, you cannot monitor its direct parent or its children. Given the root of the tree, calculate the maximum total value you can secure.

Function Signature

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def max_value_linear(v: List[int]) -> int:
    pass

def max_value_tree(root: TreeNode) -> int:
    pass

Constraints

  • For linear: 1 <= len(v) <= 10^5
  • For tree: Number of nodes is between 1 and 10^4
  • Values v[i] are between 0 and 10^4

Edge Cases

  • Empty lists or trees.
  • Linear arrays with 1 or 2 elements.
  • Skewed trees (essentially a linked list).

Hints

Hint 1

For the linear version, define a state `dp[i]` as the maximum value achievable considering units up to index `i`.

Hint 2

For the tree version, consider returning two values for each node: the max value if the node is included and the max value if it is excluded.

Hint 3

In the tree recursion, if you choose to include a node, you must force the exclusion of its immediate children.

Follow-up questions

  • How would you modify the linear solution if the storage units were arranged in a circle, meaning the first and last units are adjacent?
  • Can you solve the linear version using only O(1) space instead of O(n)?
  • What would change if each node in the tree had a 'weight' indicating the cost to monitor it, and you had a total budget constraint?