NeetCode #660LC-198Medium1-D Dynamic ProgrammingBlind 75NC 150NC 250
← Back to All Problems#660 · #198 · House Robber(打家劫舍)
📌 Problem Statement & Constraints
You are given a non-negative integer array
nums where nums[i] is the money in house i. Return the maximum amount you can rob without robbing two adjacent houses. Constraints: 1 <= nums.length <= 100, 0 <= nums[i] <= 400.💡 Core Algorithmic Approaches
- Let
dp[i]be the maximum loot considering houses0..i. - At house
iyou either skip it (dp[i - 1]) or rob it (nums[i] + dp[i - 2]), sodp[i] = max(dp[i - 1], nums[i] + dp[i - 2]). - The two choices are exhaustive because robbing
iforbids exactlyi - 1. - Keep only the last two values to obtain O(1) space.
💻 Benchmark Python3 Implementation
class Solution:
def rob(self, nums: List[int]) -> int:
prev2, prev1 = 0, 0 # dp[i-2], dp[i-1]
for x in nums:
prev2, prev1 = prev1, max(prev1, prev2 + x)
return prev1⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass over the houses.
💾 Space Complexity
O(1): two rolling values.
⚠️ Interview Pitfalls & Follow-ups
- Robbing every other house greedily: for
[2, 1, 1, 2]the greedy picks 2 + 1 = 3, but robbing indices 0 and 3 gives 4. - Always robbing the current house: you must take the max with the skip option, otherwise
[2, 1]would wrongly return 3. - Indexing
dp[i - 2]for the first house: initialise both rolling values to 0 soi = 0uses the empty prefix. - Sorting the houses: adjacency is positional, so any reordering changes the problem.