Problem overview
The method rob receives a vector nums where nums[i] is the money in house i. You may rob any set of houses as long as no two neighbours are both robbed. It returns the largest total you can collect.
For nums = [2, 7, 9, 3, 1] the answer is 12: robbing houses 0, 2 and 4 gives 2 + 9 + 1. The third example, [2, 1, 1, 2], shows that the best plan can skip two houses in a row: robbing the two ends gives 4, while robbing every other house gives only 3.
Approach: rob it or skip it
Go through the houses from left to right and decide each one. For house i there are two choices:
- Skip it. The best total is then the best total for the houses before it.
- Rob it. Then house
i - 1must stay untouched, so the money in houseiis added to the best total for the houses before housei - 1.
The better of the two is the best total up to house i. Each decision needs only two earlier answers, so two running totals are all the program keeps. This is dynamic programming: every answer is built from answers to smaller versions of the problem.
Why two totals are enough: whether house i is robbed only changes what is allowed for house i - 1. Nothing earlier than that can clash with it, so the best totals for the two most recent prefixes carry all the information the next decision needs.
Step by step
- Create
prevas 0. At the start of each round it is the best total for the houses up to two before the current one. - Create
curras 0. It is the best total for the houses up to the one just before the current one. Before the first house nothing has been robbed, so both are 0. - Loop over every house with an index
ifrom 0 whilei < nums.size(). Each house is decided exactly once. - Compute
bestasmax(curr, prev + nums[i]): skip the house and keepcurr, or rob it and add its money toprev. - Slide both totals one house to the right.
prevtakescurr, thencurrtakesbest. Doing it the other way round would overwrite the valueprevneeds. - Return
curr. After the last house it is the best total for the whole street.
The solution in C++
class Solution {
public:
int rob(vector<int>& nums) {
int prev = 0;
int curr = 0;
for (int i = 0; i < nums.size(); i++) {
int best = max(curr, prev + nums[i]);
prev = curr;
curr = best;
}
return curr;
}
};
For nums = [2, 7, 9, 3, 1] the variables change like this, with prev and curr shown after the round:
i | nums[i] | best | prev | curr |
|---|---|---|---|---|
| 0 | 2 | 2 | 0 | 2 |
| 1 | 7 | 7 | 2 | 7 |
| 2 | 9 | 11 | 7 | 11 |
| 3 | 3 | 11 | 11 | 11 |
| 4 | 1 | 12 | 11 | 12 |
At house 3 the money (3) added to prev (7) gives 10, which is less than curr (11), so the house is skipped and the total stays at 11. At house 4, robbing wins: 11 + 1 = 12.
The example [2, 1, 1, 2] shows why comparing both options matters. After each round curr is 2, 2, 3 and 4. At house 1, robbing would give 0 + 1 = 1, less than the 2 already kept, so the house is skipped. At house 2, robbing gives 2 + 1 = 3 and wins. At house 3, prev is 2, so robbing gives 2 + 2 = 4, which beats the 3 from skipping. The final plan robs houses 0 and 3 and leaves two houses in a row alone.
The C++ details:
vector<int>& numstakes the vector by reference, so no copy is made. The function only reads it.maxcomes from the standard library and needs both arguments to have the same type, which they do here (intandint).nums.size()is unsigned. Comparing it with the signediis fine here becauseinever goes below zero, but the compiler may warn about it. With an empty vector,nums.size() - 1would wrap around to a huge number, which is why the loop usesi < nums.size()and noti <= nums.size() - 1.
Complexity
Time: O(n), where n is the number of houses: one pass, constant work per house.
Space: O(1): prev, curr, best and the loop index, whatever the street's length.
Edge cases and common mistakes
- One house.
[5]returns 5:best = max(0, 0 + 5). - All zeros.
[0, 0]returns 0. Zero is allowed by the constraints, and nothing special is needed. - Taking every other house. It looks natural but fails: for
[2, 1, 1, 2]it gives 3, while the code returns 4. For[10, 1, 1, 10]the answer is 20, from the two ends. - Greedy by the largest house. Robbing the biggest house first can block two good neighbours. The two-choice rule compares both options at every house instead.
- Starting the totals at something other than 0. With
prevandcurrboth 0, the first house follows the same rule as every other house. A special start value would need a special case for it.
Testing
[1, 2, 3, 1]gives4.[2, 7, 9, 3, 1]gives12.[2, 1, 1, 2]gives4.[5]gives5.[10, 1, 1, 10]gives20.[4, 1, 2, 7, 5, 3, 1]gives14.
