Skip to content

House Robber

MediumLeetCode #198Time O(n)Space O(1)

Each house in a row holds some cash. If you rob two neighboring houses the alarm goes off, so you may never rob adjacent houses. Return the most money you can take.

nums = [2, 7, 9, 3, 1] -> 12 (rob 2 + 9 + 1)

Brute force tries every subset with no two adjacent, which is O(2^n). Greedy (“always take the biggest”) fails: in [2, 3, 2] it takes the 3 and then can take nothing else, but the best is 2 + 2.

At each house you make one choice: skip it, or rob it and give up the previous house. So best[i] = max(best[i-1], best[i-2] + nums[i]), with best of nothing equal to 0. Each value depends only on the previous two, so two rolling variables are enough.

Show solutionHide solution
def rob(nums: list[int]) -> int:
two_back, one_back = 0, 0 # best loot up to i-2 and up to i-1
for money in nums:
two_back, one_back = one_back, max(one_back, two_back + money)
return one_back
  • Time: O(n) — one pass, constant work per house.
  • Space: O(1) — two variables replace the full best array.
  • Update both variables together. Overwriting one_back before using it to set two_back mixes up the two houses. Use a tuple swap or a temp variable.
  • Short inputs. One house must return its value, and an array of zeros must return 0. Starting both variables at 0 handles these without special cases.
  • Don’t think “alternate houses”. The best plan can skip two in a row, such as [100, 1, 1, 100].

The houses form a circle, so the first and last are neighbors. The trick: run the linear solution twice, once on nums[0..n-2] and once on nums[1..n-1], and take the larger result. Handle n = 1 separately.

Taking value v earns v points but deletes every v-1 and v+1. The trick: sum the points per value into an array indexed by value. Then it is exactly House Robber on that array, because picking v forbids its neighbors.