Coding Interview PatternsHouse Robber
MediumDynamic Programming
House Robber
Explanation & Solution
Description
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 is that adjacent houses have security systems connected — if two adjacent houses are broken into on the same night, the police will be alerted.
Given an integer array nums representing the amount of money at each house, return the maximum amount of money you can rob tonight without alerting the police.
Input:nums = [1,2,3,1]
0
1
1
2
2
3
3
1
Output: 4
Explanation: Rob house 0 (money = 1) and then rob house 2 (money = 3). Total = 1 + 3 = 4.
Constraints
1 <= nums.length <= 1000 <= nums[i] <= 400
Approach
Dynamic Programming pattern
1. Define the Subproblem
- Let
dp[i]be the maximum money you can rob from houses0throughi - At each house
i, you have two choices: rob it or skip it
2. Write the Recurrence
- If you rob house
i: you cannot rob housei - 1, so the best isdp[i - 2] + nums[i] - If you skip house
i: the best remainsdp[i - 1] - Therefore
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])
3. Establish Base Cases
dp[-1] = 0(no houses to rob)dp[0] = nums[0](only one house, rob it)- We use
prev2 = 0andprev1 = 0then iterate, which handles these naturally
4. Optimize Space
- Since
dp[i]only depends ondp[i - 1]anddp[i - 2], we only need two variables prev2tracks the value two steps back,prev1tracks the value one step back- Update both as we iterate through each house
5. Return the Result
- After processing all houses,
prev1holds the maximum amount that can be robbed
Key Insight
- This is a classic decision at each step DP: rob or skip, where robbing prevents taking the neighbor
Time
O(n)single pass through the arraySpace
O(1)only two variables maintainedVisualization
Input:
Dynamic Programmingnums = [1,2,3,1]
dp
Press play to start DP animation
ComputingDependencyFilledEmpty
5 steps