House Robber
LeetCode #198 · Medium · Dynamic Programming · C++ solution with worked-out approach and complexity analysis.
Approach
Dynamic Programming with O(1) Space
At each house, we have two choices: 1. Rob this house: total = (best up to i-2) + nums[i] 2. Skip this house: total = (best up to i-1) The answer is the max of these two: dp[i] = max(dp[i-1], dp[i-2] + nums[i]). Since dp[i] only depends on the previous two values, we can collapse the table to two rolling variables.
Strategy
- 1Track `curr` (best up to the previous house) and `prev` (best up to two
- 2For each house, compute `take = prev + money` (rob this house).
- 3Shift: prev becomes the old curr, curr becomes max(take, curr) — i.e.,
- 4After the loop, curr holds the answer.
Problem description(from LeetCode)
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.
Examples
- Input:
- nums = [1,2,3,1]
- Output:
- 4
- Note:
- Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
- Input:
- nums = [2,7,9,3,1]
- Output:
- 12
- Note:
- Rob house 1, house 3, and house 5: 2 + 9 + 1 = 12.
Constraints
- •1 <= nums.length <= 100
- •0 <= nums[i] <= 400
C++ Solution
class Solution {
public:
int rob(vector<int> &nums) {
int curr = 0, prev = 0;
for (auto money : nums) {
int take = prev + money;
prev = curr;
curr = max(take, curr);
}
return curr;
}
};