House Robber
Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #198
Houses on a street hold nums[i] amounts of money. You can't take from two adjacent houses (the alarm triggers). Return the maximum total you can collect.
Examples
text
nums = [2, 7, 9, 3, 1] → 12 (2 + 9 + 1)
nums = [5, 1, 1, 5] → 10 (5 + 5)Hints
- For house i, either you skip it, or you take it and must have skipped house i−1.
- dp[i] = best total using houses 0..i.
Approach
State: dp[i] = maximum loot from houses 0..i. For house i: skip it (dp[i−1]) or take it plus the best up to i−2 (dp[i−2] + nums[i]). Take the max. Only the two previous values matter, so roll them in variables prev2, prev1.
Complexity
Time: O(n). Space: O(1).
Python solution
def rob(nums):
prev2 = prev1 = 0
for x in nums:
prev2, prev1 = prev1, max(prev1, prev2 + x)
return prev1JavaScript solution
function rob(nums) {
let prev2 = 0, prev1 = 0;
for (const x of nums) [prev2, prev1] = [prev1, Math.max(prev1, prev2 + x)];
return prev1;
}