101. House Robber
View on NeetCode
View on LeetCode
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.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 400
Solution
Approach 1: Dynamic Programming (Bottom-Up)
The key insight is that for each house, we choose the maximum between: robbing it (adding its value to max from two houses back) or skipping it (taking max from previous house).
Implementation
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) <= 2:
return max(nums)
n = len(nums)
dp = [0] * n
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, n):
dp[i] = max(dp[i-1], dp[i-2] + nums[i])
return dp[-1]
Approach 2: Space-Optimized DP
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) <= 2:
return max(nums)
prev2 = nums[0]
prev1 = max(nums[0], nums[1])
for i in range(2, len(nums)):
current = max(prev1, prev2 + nums[i])
prev2 = prev1
prev1 = current
return prev1
Approach 3: Even More Concise
class Solution:
def rob(self, nums: List[int]) -> int:
rob1, rob2 = 0, 0
for num in nums:
new_rob = max(rob2, rob1 + num)
rob1 = rob2
rob2 = new_rob
return rob2
Complexity Analysis
- Time Complexity: O(n), where n is the number of houses.
- Space Complexity: O(1) for space-optimized versions, O(n) for version with dp array.
Key Insights
-
Decision at Each House: At house i, we either rob it or skip it. If we rob it, we can’t rob house i-1.
- Recurrence Relation:
dp[i] = max(dp[i-1], dp[i-2] + nums[i])dp[i-1]: skip current house, take max from previousdp[i-2] + nums[i]: rob current house, add to max from two houses back
- Base Cases:
- One house: rob it
- Two houses: rob the one with more money
-
Running Maximum: We’re always tracking the maximum money we can rob up to the current house.
- Space Optimization: Only need previous two values, so we can use O(1) space.