This is LeetCode #198: House Robber — one of the best problems to learn DP! 🏠
💡 Think of it like this: You're a robber looking at a row of houses, each with some money. But there's an alarm — if you rob two houses that are next to each other, the police come! How do you maximize your loot?
The DP Insight: At each house, you have exactly 2 choices:
Recurrence: dp[i] = max(dp[i-1], dp[i-2] + nums[i])
💭 Time to code! Use the step-by-step approach described above. Don't peek at the solution — try first! 🚀
Step-by-step trace for [2, 7, 9, 3, 1]:
Complexity: Time O(n), Space O(1). Clean!
def rob(nums):
if not nums: return 0
if len(nums) == 1: return nums[0]
# Only need previous two values (O(1) space!)
prev2 = 0 # max profit 2 houses ago
prev1 = 0 # max profit at previous house
for num in nums:
current = max(prev1, prev2 + num) # Skip or rob?
prev2 = prev1
prev1 = current
return prev1
rob([2, 7, 9, 3, 1])
12