← Back to All Algorithms

Medium Interview Frequency: ⭐⭐⭐⭐

House Robber

You cannot rob adjacent houses. Return the maximum amount of money you can steal from nums without triggering alarms.

Dynamic Programming State Transition

📚 Table of Contents

  1. Problem Statement
  2. Real-World Analogy
  3. Key Insights
  4. Solution Approaches
  5. Step-by-Step Walkthrough
  6. Complexity Analysis
  7. Edge Cases
  8. Test Cases
  9. Interview Tips
  10. Related Problems
  11. Key Takeaways

📋 Problem Statement

Given non-negative integers representing money in each house, maximize stolen money with the rule: you cannot choose two neighboring indices.

Examples

Example 1:
Input: [1,2,3,1]
Output: 4
Rob houses 1 and 3: 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1]
Output: 12
Rob houses 1, 3, 5 style choice: 2 + 9 + 1 = 12.

🎯 Real-World Analogy

Choosing Non-Adjacent Time Slots

You have paid meetings in a timeline but cannot attend back-to-back slots. At each slot, decide: take this one (skip previous) or skip this one (keep previous best).

💡 Key Insights

💻 Solution Approaches

Approach 1: Top-Down Memoization

Time: O(N) | Space: O(N)

Approach 2: Bottom-Up O(1) Space (Recommended)

Time: O(N) | Space: O(1)

Python Implementation

from typing import List def rob(nums: List[int]) -> int: prev2 = 0 # best up to i-2 prev1 = 0 # best up to i-1 for value in nums: take = prev2 + value skip = prev1 current = max(take, skip) prev2 = prev1 prev1 = current return prev1

JavaScript Implementation

function rob(nums) { let prev2 = 0; let prev1 = 0; for (const value of nums) { const take = prev2 + value; const skip = prev1; const current = Math.max(take, skip); prev2 = prev1; prev1 = current; } return prev1; }

🔍 Step-by-Step Walkthrough

Trace [2,7,9,3,1]:

Start: prev2=0, prev1=0
2 -> max(0+2,0)=2
7 -> max(0+7,2)=7
9 -> max(2+9,7)=11
3 -> max(7+3,11)=11
1 -> max(11+1,11)=12

⚡ Complexity Analysis

Time: O(N) because each house is processed once.

Space: O(1) using two rolling states.

🔧 Edge Cases

🧪 Test Cases

Python

def test_rob(): assert rob([1,2,3,1]) == 4 assert rob([2,7,9,3,1]) == 12 assert rob([]) == 0 assert rob([5]) == 5 assert rob([2,1,1,2]) == 4 print("✅ all tests passed")

JavaScript

function testRob() { console.assert(rob([1,2,3,1]) === 4, "test 1"); console.assert(rob([2,7,9,3,1]) === 12, "test 2"); console.assert(rob([]) === 0, "test 3"); console.log("✅ all tests passed"); }

💼 Interview Tips

🎓 Key Takeaways

← Back to All Algorithms