Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 337 House Robber III - State Design

Two values per node

For each node, compute two values: rob[v]\text{rob}[v] = max money if you rob vv, and skip[v]\text{skip}[v] = max money if you skip vv.

Transitions: rob[v]=v.val+skip[left]+skip[right]\text{rob}[v] = v.\text{val} + \text{skip}[\text{left}] + \text{skip}[\text{right}], and skip[v]=max(rob[left],skip[left])+max(rob[right],skip[right])\text{skip}[v] = \max(\text{rob}[\text{left}], \text{skip}[\text{left}]) + \max(\text{rob}[\text{right}], \text{skip}[\text{right}]).

Answer: max(rob[root],skip[root])\max(\text{rob}[\text{root}], \text{skip}[\text{root}]).