InterviewPrepKit

Home / Coding / 1-D Dynamic Programming

House Robber

medium Original β†—
Solving tips
  • Canonical take-it-or-leave-it DP: best(i) = max(best(i-1), best(i-2) + nums[i]) - skip house i, or rob it and jump two back.
  • Greedy 'rob every other house' fails (e.g. [2,1,1,2]); the max in the recurrence is essential.
  • Seed two rolling scalars to 0 to fold in the base cases and dodge the n==1 special case, giving O(n) time, O(1) space.
  • The constraint is on array positions (index-neighbors), not on values, so 0-valued houses still obey the recurrence.

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 β€” a single house, just take it.

Constraints

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

Small input, so O(n) is trivial; 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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.