#337

House Robber III

Medium DP on trees

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Houses form a binary tree; robbing two directly linked houses triggers the alarm. Return the most money you can rob.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: rob a tree of houses without robbing a parent and its child.

Why this works: each node returns two numbers: best if robbed, best if skipped. The parent combines them.

Example: 3 (2 (-, 3), 3 (-, 1))

rob root + grandchildren: 3 + 3 + 1 = 7

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Plain recursion that tries grandchildren directly without returning both states — exponential.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(h).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon