01
Problem Statement
You are a robber planning to rob houses along a street. Each house i has a non-negative amount of money nums[i]. You cannot rob two adjacent houses (if you rob house i, you cannot rob house i-1 or i+1). Return the maximum amount of money you can rob tonight.
- The array
numsgives the money at each house; you can choose which houses to rob subject to the no-adjacent constraint. - Empty array: return 0. Single house: return that house's value.
02
Key Observations
- At each house
i, we have two choices: rob it (then we cannot have robbedi-1, so we takenums[i] + best from [0..i-2]) or skip it (then we takebest from [0..i-1]). Sodp[i] = max(dp[i-1], nums[i] + dp[i-2]). dp[i]represents the maximum money we can get from the firsti+1houses (indices 0..i) subject to the constraint. Base:dp[0] = nums[0],dp[1] = max(nums[0], nums[1]).- We only need the last two values, so space can be O(1).
03
Approach
High-level: dp[i] = maximum money from houses [0..i] with no two adjacent robbed. Transition: either skip house i (dp[i-1]) or rob house i (nums[i] + dp[i-2]). Take the maximum.
Steps:
- If
numsis empty, return 0. If length 1, returnnums[0]. Setprev2 = nums[0],prev1 = max(nums[0], nums[1]). - For
ifrom 2 to n-1:cur = max(prev1, nums[i] + prev2); thenprev2 = prev1,prev1 = cur. - Return
prev1.
04
Implementation
Java
public int rob(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
if (n == 1) {
return nums[0];
}
int prev2 = nums[0], prev1 = Math.max(nums[0], nums[1]);
for (int i = 2; i < n; i++) {
int cur = Math.max(prev1, nums[i] + prev2);
prev2 = prev1;
prev1 = cur;
}
return prev1;
}05
Test Cases
Example 1
Input
nums = [1,2,3,1]
Expected
4Explanation
Rob house 0 and 2.
06
Complexity Analysis
- Time: O(n).
- Space: O(1).
07
Follow-ups
- House Robber II: houses are arranged in a circle (first and last adjacent).