15% off all plans & roadmaps Use code
See plansHouse Robber
- LeetCode 198
- Medium
- Dynamic Programming (DP) Patterns
- 1D Array (Fibonacci Style)
Updated
TL;DR: Pick houses along a street so that no two chosen houses are neighbors, and maximize the total money. At each house you either skip it or rob it plus the best total from two houses back, which needs only two running variables.
Problem
You are a professional robber planning to rob houses along a street. Each house holds some money. Adjacent houses share a security system, and it contacts the police if two adjacent houses are broken into on the same night.
Given an integer array nums where nums[i] is the money in house i, return the maximum amount you can rob tonight without alerting the police.
Example 1
Input: nums = [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1), then rob house 3 (money = 3). The total is 1 + 3 = 4.
Example 2
Input: nums = [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), house 3 (money = 9) and house 5 (money = 1). The total is 2 + 9 + 1 = 12.
Constraints
1 <= nums.length <= 1000 <= nums[i] <= 400
Constraints that matter
nums.lengthis at most 100, but a two-way recursion that branches at every house makes about 2^n calls in the worst case. Brute force is therefore far too slow even for this small n.- Every
nums[i]is at least 0, so skipping a house never helps you by itself. You never need to worry about negative values or about forcing a pick. - The largest possible total is 100 * 400 = 40,000 at most, which fits in a 32-bit integer in every language. You do not need
longor big integers. nums.lengthis at least 1, so there is always a first house. You still want a recurrence that works with zero houses, because it removes special cases.- Only the two previous answers feed the next one, so O(1) extra space is possible.
Hints
Hint 1
This is dynamic programming on a line.
Hint 2
Try every legal choice.
Solution
Intuition
This is dynamic programming on a line. Look at the last house. Either you rob it or you do not, and each choice leaves a smaller version of the same problem.
Picture two sticky notes stacked on a desk, with the top note holding prev1 and the note beneath it holding prev2. Each house writes a new top note with the larger option, the old top slides down, and the bottom note falls off.
If you rob house i, house i - 1 is off limits. Your total is nums[i] plus the best you can do on houses 0..i-2. If you skip house i, your total is the best you can do on houses 0..i-1. The answer for the first i + 1 houses is the larger of those two numbers.
The best total for a prefix does not depend on which houses produced it. Only the number matters. So each prefix answer needs only two earlier answers, and the same prefix answers get reused many times. That repeated work makes plain recursion exponential, and a table or two variables removes it.
The recurrence has the same shape as Fibonacci, with max in place of +. Write best[i] = max(best[i-1], best[i-2] + nums[i]) and treat the best of an empty prefix as 0. Then no base-case branching is needed.
Worked example
Input: nums = [6, 7, 1, 30, 8, 2, 4] Output: 41 Explanation: Rob the houses holding 7, 30 and 4. They sit at indices 1, 3 and 6, so no two are adjacent, and 7 + 30 + 4 = 41. Taking 6, 1, 8 and 4 gives only 19, and taking 6, 30 and 4 gives 40, so 41 is the best.
Approach 1: Brute force recursion
Try every legal choice. For house i, you either rob it and move on to house i - 2, or skip it and move on to house i - 1. Take the larger result. When the index drops below 0, there are no houses left and the result is 0.
These two options cover every legal plan for the first i + 1 houses, so the answer is correct. It is slow because nothing is remembered.
Steps
- Define
best(i)as the most money you can rob from houses0..i. - If
i < 0, return 0. - Compute
skip = best(i - 1). - Compute
take = nums[i] + best(i - 2). - Return the larger of
skipandtake. - Call
best(n - 1)and return that value.
Dry run
Run on [6, 7, 1, 30, 8, 2, 4]. The call best(6) becomes max(best(5), 4 + best(4)).
The call best(5) becomes max(best(4), 2 + best(3)), so best(4) is already evaluated twice. Each of those calls best(3), so best(3) runs three times in total, and the repeats keep multiplying toward the leaves.
When the tree finally bottoms out, the values are best(5) = 39 and best(4) = 37. Then best(6) = max(39, 4 + 37) = 41. Counting every call including the ones that return 0 at a negative index, this tiny input already makes 67 calls.
Complexity
| Time | O(2^n) |
|---|---|
| Space | O(n) |
Here n is the number of houses. Each call with index i makes two calls, one with i - 1 and one with i - 2, so the call count follows T(i) = 1 + T(i-1) + T(i-2). That grows like Fibonacci numbers, which is exponential in n, roughly 1.6^n and bounded by 2^n. The recursion depth is at most n, so the call stack uses O(n) space.
PythonTested in our runner
from typing import List, Optional
class Solution:
def rob(self, nums: List[int]) -> int:
def best(i: int) -> int:
# No houses left to consider
if i < 0:
return 0
skip = best(i - 1)
take = nums[i] + best(i - 2)
return max(skip, take)
return best(len(nums) - 1)
JavaTested in our runner
import java.util.*;
class Solution {
public int rob(int[] nums) {
return best(nums, nums.length - 1);
}
private int best(int[] nums, int i) {
// No houses left to consider
if (i < 0) {
return 0;
}
int skip = best(nums, i - 1);
int take = nums[i] + best(nums, i - 2);
return Math.max(skip, take);
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
return best(nums, (int)nums.size() - 1);
}
private:
int best(vector<int>& nums, int i) {
// No houses left to consider
if (i < 0) {
return 0;
}
int skip = best(nums, i - 1);
int take = nums[i] + best(nums, i - 2);
return max(skip, take);
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
const best = (i) => {
// No houses left to consider
if (i < 0) return 0;
const skip = best(i - 1);
const take = nums[i] + best(i - 2);
return Math.max(skip, take);
};
return best(nums.length - 1);
};
GoTested in our runner
func rob(nums []int) int {
var best func(i int) int
best = func(i int) int {
// No houses left to consider
if i < 0 {
return 0
}
skip := best(i - 1)
take := nums[i] + best(i-2)
if take > skip {
return take
}
return skip
}
return best(len(nums) - 1)
}
C#Tested in our runner
public class Solution {
public int rob(int[] nums) {
return Best(nums, nums.Length - 1);
}
private int Best(int[] nums, int i) {
// No houses left to consider
if (i < 0) {
return 0;
}
int skip = Best(nums, i - 1);
int take = nums[i] + Best(nums, i - 2);
return Math.Max(skip, take);
}
}
Approach 2: Memoized recursion
What's slow: best(i) is recomputed every time some larger call needs it. In the trace above, best(3) ran three times, and the repeats grow with every extra house.
The insight that fixes it: best(i) depends only on i, never on how you got there. Compute each index once, store it in an array, and return the stored value on every later visit. There are only n distinct indices, so there are only n real computations.
Steps
- Create a
memoarray of size n filled with -1, meaning not computed yet. - In
best(i), return 0 wheni < 0. - If
memo[i]is not -1, return it. - Compute
max(best(i - 1), nums[i] + best(i - 2)). - Store that value in
memo[i]and return it. - Return
best(n - 1).
Dry run
Run on [6, 7, 1, 30, 8, 2, 4]. The first call best(6) calls best(5), which calls down the chain to best(0).
best(0) stores memo[0] = 6. Then best(1) = max(6, 7) = 7, best(2) = max(7, 6 + 1) = 7, best(3) = max(7, 7 + 30) = 37, best(4) = max(37, 7 + 8) = 37, and best(5) = max(37, 37 + 2) = 39.
Back at best(6), the second branch needs best(4). That is a memo hit, so it returns 37 at once. The result is max(39, 4 + 37) = 41.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Here n is the number of houses. Each index is computed once, because afterwards its memo entry is filled, and each computation does O(1) work plus two lookups. That is at most 2n + 1 calls in total. The memo array holds n integers and the recursion goes n levels deep, so space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def rob(self, nums: List[int]) -> int:
memo = [-1] * len(nums)
def best(i: int) -> int:
if i < 0:
return 0
if memo[i] != -1:
return memo[i]
# Skip house i, or rob it and jump back two houses
memo[i] = max(best(i - 1), nums[i] + best(i - 2))
return memo[i]
return best(len(nums) - 1)
JavaTested in our runner
import java.util.*;
class Solution {
public int rob(int[] nums) {
int[] memo = new int[nums.length];
Arrays.fill(memo, -1);
return best(nums, nums.length - 1, memo);
}
private int best(int[] nums, int i, int[] memo) {
if (i < 0) {
return 0;
}
if (memo[i] != -1) {
return memo[i];
}
// Skip house i, or rob it and jump back two houses
memo[i] = Math.max(best(nums, i - 1, memo), nums[i] + best(nums, i - 2, memo));
return memo[i];
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
vector<int> memo(nums.size(), -1);
return best(nums, (int)nums.size() - 1, memo);
}
private:
int best(vector<int>& nums, int i, vector<int>& memo) {
if (i < 0) {
return 0;
}
if (memo[i] != -1) {
return memo[i];
}
// Skip house i, or rob it and jump back two houses
memo[i] = max(best(nums, i - 1, memo), nums[i] + best(nums, i - 2, memo));
return memo[i];
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
const memo = new Array(nums.length).fill(-1);
const best = (i) => {
if (i < 0) return 0;
if (memo[i] !== -1) return memo[i];
// Skip house i, or rob it and jump back two houses
memo[i] = Math.max(best(i - 1), nums[i] + best(i - 2));
return memo[i];
};
return best(nums.length - 1);
};
GoTested in our runner
func rob(nums []int) int {
memo := make([]int, len(nums))
for i := range memo {
memo[i] = -1
}
var best func(i int) int
best = func(i int) int {
if i < 0 {
return 0
}
if memo[i] != -1 {
return memo[i]
}
// Skip house i, or rob it and jump back two houses
skip := best(i - 1)
take := nums[i] + best(i-2)
if take > skip {
skip = take
}
memo[i] = skip
return skip
}
return best(len(nums) - 1)
}
C#Tested in our runner
public class Solution {
public int rob(int[] nums) {
int[] memo = new int[nums.Length];
for (int k = 0; k < memo.Length; k++) {
memo[k] = -1;
}
return Best(nums, nums.Length - 1, memo);
}
private int Best(int[] nums, int i, int[] memo) {
if (i < 0) {
return 0;
}
if (memo[i] != -1) {
return memo[i];
}
// Skip house i, or rob it and jump back two houses
memo[i] = Math.Max(Best(nums, i - 1, memo), nums[i] + Best(nums, i - 2, memo));
return memo[i];
}
}

Solution pattern
1D Array (Fibonacci Style)
Approach 3: Bottom-up DP with two variablesOptimal1D Array (Fibonacci Style)
What's slow: memoization is linear in time, but it still stores n values and recurses n levels deep. Every stored value except the last two is never read again.
The insight that fixes it: walk the houses left to right and keep only prev1, the best total up to the previous house, and prev2, the best total up to the house before that. Both start at 0, which stands for an empty prefix. At each house compute max(prev1, prev2 + num), then shift the two variables forward. No base cases and no array are needed.
Steps
- Set
prev2 = 0andprev1 = 0. - For each
numinnums, computecur = max(prev1, prev2 + num). - Set
prev2 = prev1. - Set
prev1 = cur. - After the loop, return
prev1.
Dry run
Run on [6, 7, 1, 30, 8, 2, 4]. Both variables start at 0. The table shows the state before each step and the result.
| i | num | prev2 | prev1 | prev2 + num | cur = max(prev1, prev2 + num) | state after (prev2, prev1) |
|---|---|---|---|---|---|---|
| 0 | 6 | 0 | 0 | 6 | 6 | (0, 6) |
| 1 | 7 | 0 | 6 | 7 | 7 | (6, 7) |
| 2 | 1 | 6 | 7 | 7 | 7 | (7, 7) |
| 3 | 30 | 7 | 7 | 37 | 37 | (7, 37) |
| 4 | 8 | 7 | 37 | 15 | 37 | (37, 37) |
| 5 | 2 | 37 | 37 | 39 | 39 | (37, 39) |
| 6 | 4 | 37 | 39 | 41 | 41 | (39, 41) |
The loop ends with prev1 = 41, which matches the expected output. Rows 2 and 4 show a skip: robbing the house would not beat the running best.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the number of houses. The loop runs exactly n times and each pass does one addition, one comparison and two assignments, so time is O(n). The only state is the two integers prev1 and prev2 plus the loop variable, which does not grow with n, so space is O(1). Correctness follows by induction: after step i, prev1 is the best total for houses 0..i and prev2 is the best for 0..i-1.
PythonTested in our runner
from typing import List, Optional
class Solution:
def rob(self, nums: List[int]) -> int:
prev2 = 0 # best total up to two houses back
prev1 = 0 # best total up to the previous house
for num in nums:
# Skip this house, or rob it on top of prev2
cur = max(prev1, prev2 + num)
prev2 = prev1
prev1 = cur
return prev1
JavaTested in our runner
import java.util.*;
class Solution {
public int rob(int[] nums) {
int prev2 = 0; // best total up to two houses back
int prev1 = 0; // best total up to the previous house
for (int num : nums) {
// Skip this house, or rob it on top of prev2
int cur = Math.max(prev1, prev2 + num);
prev2 = prev1;
prev1 = cur;
}
return prev1;
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
int prev2 = 0; // best total up to two houses back
int prev1 = 0; // best total up to the previous house
for (int num : nums) {
// Skip this house, or rob it on top of prev2
int cur = max(prev1, prev2 + num);
prev2 = prev1;
prev1 = cur;
}
return prev1;
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
let prev2 = 0; // best total up to two houses back
let prev1 = 0; // best total up to the previous house
for (const num of nums) {
// Skip this house, or rob it on top of prev2
const cur = Math.max(prev1, prev2 + num);
prev2 = prev1;
prev1 = cur;
}
return prev1;
};
GoTested in our runner
func rob(nums []int) int {
prev2 := 0 // best total up to two houses back
prev1 := 0 // best total up to the previous house
for _, num := range nums {
// Skip this house, or rob it on top of prev2
cur := prev2 + num
if prev1 > cur {
cur = prev1
}
prev2 = prev1
prev1 = cur
}
return prev1
}
C#Tested in our runner
public class Solution {
public int rob(int[] nums) {
int prev2 = 0; // best total up to two houses back
int prev1 = 0; // best total up to the previous house
foreach (int num in nums) {
// Skip this house, or rob it on top of prev2
int cur = Math.Max(prev1, prev2 + num);
prev2 = prev1;
prev1 = cur;
}
return prev1;
}
}
Common mistakes
- Returning the larger of the even-index sum and the odd-index sum. On
[100, 1, 1, 100]both sums are 101, but robbing indices 0 and 3 gives 200. Use the recurrence, which allows a gap of more than one house. - Writing
nums[i] + best(i - 1)in the rob branch. Adjacent houses cannot both be robbed, so the rob branch must jump toi - 2. - Reading
dp[i - 2]in an array version without handlingi < 2. That is an out-of-bounds read. Either guard the first two indices, pad with a leading 0, or use two variables that start at 0. - Updating
prev1before copying it intoprev2. Afterprev1 = cur, the old value is lost andprev2ends up equal toprev1. Savecurfirst, assignprev2 = prev1, then assignprev1 = cur. - Returning
prev2instead ofprev1at the end. After the last shift,prev1holds the answer for the whole array andprev2holds the answer without the last house. - Submitting the plain two-branch recursion. It is correct but makes about 1.6^n calls, so it times out when n is near 100. Add a memo or switch to the loop.
Edge cases
[5]: one house. The loop runs once,max(0, 0 + 5) = 5, so the answer is 5.[2, 1]: two houses. You can take only one, so the answer ismax(2, 1) = 2.[0, 0, 0]: all zeros. The answer is 0, and the code must not return a negative or an uninitialized value.[100, 1, 1, 100]: the best plan skips two houses in the middle. The answer is 200, and alternating-index sums fail here.[400] * 100: maximum size and value. Robbing every other house gives 50 * 400 = 20000, well inside the int range.[1, 2, 3, 1]: the first sample. The answer is 4, from houses at indices 0 and 2.
Follow-ups interviewers ask
- What if the houses form a circle, so the first and last are adjacent?
- This is House Robber II. The first and last houses cannot both be robbed, so run the same loop twice. Run it once on
nums[0..n-2]and once onnums[1..n-1], and return the larger result. Handle n = 1 separately by returningnums[0]. - Can you return which houses to rob, not only the total?
- Keep a full table
dpof prefix answers instead of two variables. Then walk backward from the end. At indexi, ifdp[i] == dp[i-1]you skipped the house, so move toi - 1. Otherwise you robbed it, so recordiand move toi - 2. That costs O(n) space. - What if the houses form a binary tree and you cannot rob a parent and its child?
- This is House Robber III. Run a DFS that returns two numbers per node: the best total if you rob that node, and the best if you skip it. Robbing a node adds its value to the skip values of its children. Skipping it takes the larger of the two values from each child. Each node is visited once, so time is O(n).
House Robber FAQ
What is the time complexity of House Robber?
The optimal solution is O(n) time, where n is the number of houses, because it makes one pass with constant work per house. Plain recursion is O(2^n), and memoized recursion is O(n).
Why use dynamic programming for House Robber?
The best total for a prefix of houses is reused by every longer prefix, and it depends only on the two prefix answers before it. Dynamic programming computes each prefix answer once instead of re-solving it exponentially many times.
Can House Robber be solved in O(1) extra space?
Yes. The recurrence only reads the previous two answers, so two integer variables replace the whole table. You lose the ability to rebuild which houses were robbed, unless you store the full table.
Why is greedy wrong for House Robber?
Taking the largest house first, or taking every other house, can block a better pair. On [2, 7, 9, 3, 1], greedy takes 9 and then 2 and 1, getting 12 by luck. On [2, 10, 3, 3, 10], greedy takes 10 first, then 3, giving 13, while 10 + 10 = 20 is better.
Is the House Robber DP the same as Climbing Stairs?
The recurrence has the same shape, since each state depends on the previous two. Climbing Stairs adds the two values to count ways, while House Robber takes a maximum and adds the current house's money to the value two steps back.
Why initialize prev1 and prev2 to 0 in House Robber?
Zero stands for the best total of an empty set of houses. With both variables at 0, the first house gives max(0, 0 + nums[0]) = nums[0] with no special case, which also covers a one-house input.
Asked at
See which companies ask this — Pro
Related problems
- Decode Ways · same technique: 1D Array (Fibonacci Style)
- House Robber II · same technique: 1D Array (Fibonacci Style)
- Integer Break · same technique: 1D Array (Fibonacci Style)
- House Robber III · same technique: 1D Array (Fibonacci Style)
- Delete and Earn · same technique: 1D Array (Fibonacci Style)
- Distinct Subsequences · next harder, same pattern
- Coin Change · same pattern: Dynamic Programming (DP) Patterns
- Maximum Subarray · same pattern: Dynamic Programming (DP) Patterns
- Word Break · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Subsequence · same pattern: Dynamic Programming (DP) Patterns