Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 337 House Robber III - Walkthrough

Tracing the two-state DP

Rob houses on a tree where adjacent nodes can't both be robbed. Each node returns (rob,skip)(rob, skip): max money if robbed vs skipped. Example tree: root=33, left=22, right=33, left.right=33, right.right=11. Post-order builds answers bottom-up. At leaves: (value,0)(value, 0). At node 2 with child 3: rob=2+skipchild2 + skip_{child}, skip=max(robchild,skipchild)\max(rob_{child}, skip_{child}). So (2+0,3)=(2,3)(2+0, 3) = (2, 3). At root 33: left=(22,33), right=(33,11). Rob=3+3+1=73 + 3 + 1 = 7. Skip=max(2,3)+max(3,1)=3+3=6\max(2,3) + \max(3,1) = 3 + 3 = 6.

Answer: max(7,6)=7\max(7, 6) = 7.