Skip to content
DSA Patterns
Menu
Language
One-Dimensional DPLC #1983 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

House Robber

Problem (restated)

Rob houses in a line; cannot rob adjacent houses. Maximize total money.

Intuition

At each house: rob it (+ skip previous) or skip it (take previous best).

Approaches

1D DP

Unverified
Time O(n)Space O(1)

Idea. dp[i] = max(dp[i-1], dp[i-2] + nums[i]); roll two vars.

Walkthrough. [2,7,9,3,1] → 2+9+1=12 or 7+3+… best 12.

Trade-offs. O(1) space after realizing only last two states matter.

Solution
export function rob(nums: number[]): number {
  let prev2 = 0, prev1 = 0;
  for (const x of nums) {
    const cur = Math.max(prev1, prev2 + x);
    prev2 = prev1;
    prev1 = cur;
  }
  return prev1;
}
export function rob(nums: number[]): number {
  let prev2 = 0, prev1 = 0;
  for (const x of nums) {
    const cur = Math.max(prev1, prev2 + x);
    prev2 = prev1;
    prev1 = cur;
  }
  return prev1;
}

Template connection

dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]). Two rolling values store the same choice: skip this house, or rob it after skipping the previous one.

Reflection

  • dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]). Adjacent houses are forbidden. Skipping the house takes dp[i - 1].
  • One house is that house. The first two houses yield the larger of the two. All zeros is 0.
  • Two variables are enough. Walking right to left gives the same answer.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

House robber on a line [2,7,9,3,1]. Adjacent houses share an alarm.

2
0
7
1
9
2
3
3
1
4

dp[i] = max(skip, take)

Key:CurrentActive rangeMatchSettledEliminated