House Robber – Solution & Complexity
Watch: House Robber with dynamic programming
At each house you either rob it (its cash plus the best up to two houses back) or skip it (the best up to the previous house). Take the larger. Two rolling variables are enough: O(n) time, O(1) space.
Solution Walkthrough
Step 1: Understand the Choice at Each House
- At each house, you either rob it or skip it.
- If you rob the current house, you cannot rob the immediately previous one.
- The goal is the best total after considering all houses.
Step 2: Define the Dynamic Programming State
- Let
dp[i]mean the maximum money obtainable from houses up to indexi. - For each house, choose between skipping it (
dp[i - 1]) or robbing it (dp[i - 2] + nums[i]). - The recurrence is
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]).
- Let
Step 3: Optimize the Space
- The recurrence only needs the previous two results.
- Store
prev_twofordp[i - 2]andprev_onefordp[i - 1]. - Update them as you move through the array.
Step 4: Update Rolling Values
- For each amount, compute the best total if this house is included or skipped.
current = max(prev_one, prev_two + amount).- Then shift the rolling values forward.
Step 5: Final Complete Solution
- This dynamic programming solution considers every house once.
- Time complexity is O(n).
- Space complexity is O(1) because only two previous totals are stored.