House Robber - Problem

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,7,9,3,1]
Output: 12
💡 Note: Rob houses 0, 2, and 4: 2 + 9 + 1 = 12. Cannot rob adjacent houses 1 and 3.
Example 2 — Choose Larger Adjacent
$ Input: nums = [1,2,3,1]
Output: 4
💡 Note: Rob houses 0 and 2: 1 + 3 = 4, or rob houses 1 and 3: 2 + 1 = 3. The optimal choice is 4.
Example 3 — Single House
$ Input: nums = [5]
Output: 5
💡 Note: Only one house available, rob it for maximum of 5.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 400

Visualization

Tap to expand
House Robber - Space-Optimized DP INPUT $2 $7 $9 $3 $1 Input Array: nums = [2, 7, 9, 3, 1] Cannot rob adjacent houses! Security Alert: Adjacent houses are connected! ALGORITHM STEPS 1 Initialize Variables prev2=0, prev1=0 2 Iterate Houses For each house i 3 Calculate Max curr = max(prev1, prev2 + nums[i]) 4 Update Variables prev2=prev1, prev1=curr DP Trace: i: 0 1 2 3 4 nums: 2 7 9 3 1 curr: 2 7 11 11 12 FINAL RESULT Optimal Selection: $2 ROB $7 SKIP $9 ROB $3 SKIP $1 ROB $2 + $9 + $1 = $12 Houses 0, 2, 4 robbed Maximum Loot: $12 OK - Optimal! Key Insight: Space-Optimized DP uses only O(1) space by tracking just two previous states (prev1, prev2) instead of a full DP array. At each house, decide: rob it (add to prev2) or skip (keep prev1). Recurrence: dp[i] = max(dp[i-1], dp[i-2] + nums[i]) -- Time: O(n), Space: O(1) TutorialsPoint - House Robber | Space-Optimized DP Approach
Asked in
Amazon 45 Google 38 Microsoft 32 Facebook 28
67.9K Views
High Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen