House Robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. The only constraint is that adjacent houses have security systems that will alert the police if two adjacent houses are broken into on the same night. Given an array of money amounts, return the maximum amount you can rob without alerting the police.
This is a classic DP problem where the decision at each house depends on whether we robbed the previous house. The recurrence is: dp[i] = max(dp[i-1], dp[i-2] + nums[i]). Either skip the current house (keep the maximum from the previous house) or rob it (add its money to the maximum from two houses ago).
The base cases are dp[0] = nums[0] and dp[1] = max(nums[0], nums[1]). The space can be optimized to O(1) using two variables instead of an array, since each decision only depends on the two previous results. The time complexity is O(n).
Edge cases include an empty array (return 0), a single house (return its value), and two houses (return the larger one).
The house robber recurrence illustrates the fundamental DP concept of choosing between two options at each step: include or exclude. The optimal substructure property ensures that the best decision at each house depends only on the previous two subproblem results, enabling the O(1) space optimization.
Example Input & Output
Single house.
Empty array.
Only rob the first house.
Rob house 1 (1) and 3 (3). Total = 4.
Rob house 1 (2), 3 (9), 5 (1) = 12.
Algorithm Flow

Solution Approach
DP with two rolling variables. For each house, compute max of robbing it or skipping it.
Time O(n), Space O(1).
Best Answers
class Solution {
public int solution(int[] nums) {
int a = 0, b = 0;
for (int n : nums) {
int c = Math.max(a + n, b);
a = b;
b = c;
}
return b;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
