InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 1-D Dynamic Programming

House Robber

medium Original ↗ 00:00

Problem

Houses along a street each hold some amount of money, given as an array nums. You want to rob as much as possible in one night, but robbing two adjacent houses trips a shared alarm. Choose a subset of houses with no two neighbors to maximize the total money taken.

Return that maximum total.

Examples

  • nums = [1, 2, 3, 1]4 — rob houses 0 and 2 (1 + 3); robbing 1 and 3 gives only 3.
  • nums = [2, 7, 9, 3, 1]12 — rob houses 0, 2, 4 (2 + 9 + 1).
  • nums = [5]5 — the only house, so take it.

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

The input is small, so an O(n) solution is more than fast enough. The point is the no-two-adjacent decision structure, a template that recurs across many DP problems.

Think about it first

Hint 1 Consider the last house. You either rob it or you don't. If you rob it, you can't have robbed house `n-2`; if you skip it, your best is whatever you could make from the first `n-1` houses.
Hint 2 `best(i) = max( best(i-1), best(i-2) + nums[i] )` — skip house `i`, or rob it and add the best from two houses back. Base cases: `best(0) = nums[0]`, `best(1) = max(nums[0], nums[1])`.
Hint 3 Only the previous two results matter, so sweep left to right holding two rolling variables `rob_prev` and `rob_prev2`. O(n) time, O(1) space.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug