Problem overview
The function rob receives a slice nums where nums[i] is the money in house i. Two neighbouring houses can't both be robbed, and the task is to return the largest total you can take. There are between 1 and 100 houses, each holding 0 to 400.
For [2, 7, 9, 3, 1] the answer is 12: houses 0, 2 and 4 give 2 + 9 + 1. For [2, 1, 1, 2] the answer is 4, by robbing houses 0 and 3. Robbing every other house would give only 3, so skipping two houses in a row can pay off.
Approach: rob it or skip it
Decide house by house, left to right. At house i there are two choices:
- Skip it. The best total is whatever was best for the houses before it.
- Rob it. Then house
i - 1must stay untouched, so its money joins the best total for the houses up toi - 2.
The better of the two choices is the best total up to house i. That choice is the whole algorithm. Trying every subset of houses would take exponential time, but this rule needs only two earlier results, so two running totals are enough and no table is required.
The same program, run on [2, 7, 9, 3, 1], prints these values per round:
i 0 nums[i] 2 prev 0 curr 0 best 2
i 1 nums[i] 7 prev 0 curr 2 best 7
i 2 nums[i] 9 prev 2 curr 7 best 11
i 3 nums[i] 3 prev 7 curr 11 best 11
i 4 nums[i] 1 prev 11 curr 11 best 12
At house 3 the money is 3, and robbing it would give 7 + 3 = 10, which is less than the 11 already available, so the total stays at 11.
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 start at 0. - Loop over every house with
ifrom 0 whilei < len(nums). Each house is decided once. - Compute
bestas the larger ofcurr(skip the house) andprev + nums[i](rob it). - Move both totals one house to the right. Set
prevtocurrfirst, thencurrtobest, soprevgets the old value ofcurr. - Return
curr. After the last house it is the best total for the whole street.
The solution in Go
func rob(nums []int) int {
prev := 0
curr := 0
for i := 0; i < len(nums); i++ {
best := max(curr, prev+nums[i])
prev = curr
curr = best
}
return curr
}
The Go details worth a closer look:
- The built-in
max. Since Go 1.21,maxandminare built-in functions for numbers and strings, so no import and no hand-written helper is needed. The lessons use Go 1.22. - Slices carry their length.
len(nums)is the number of houses. An empty ornilslice has length 0, so the loop simply doesn't run. - Indexing is checked.
nums[i]withioutside the slice stops the program with a run-time panic, so the loop conditioni < len(nums)must be strict. bestis local to the loop body. It is created with:=in every round, whileprevandcurrkeep their values across rounds.
Complexity
Time: O(n), where n is the number of houses. Each house is visited once with constant work.
Space: O(1). Only prev, curr and best, whatever the length of the slice.
Edge cases and common mistakes
- Greedy choices. Taking every other house, or always the biggest house, can fail. For
[2, 1, 1, 2]every other house gives 3, while the answer is 4. - Overwriting in the wrong order. If
curr = bestis written beforeprev = curr, thenprevreceives the new total instead of the old one, and the next round adds to the wrong value. - A single house.
[5]gives 5:max(0, 0 + 5). - Zeros.
[0, 0, 0]gives 0. Houses with no money never hurt the totals. - Two houses.
[3, 10]gives 10, the larger of the two, because they are neighbours. - Empty slice. The constraints promise at least one house, but this code would return 0 for an empty slice.
Testing
[1, 2, 3, 1]gives4.[2, 7, 9, 3, 1]gives12.[2, 1, 1, 2]gives4.[5]gives5.[3, 10]gives10.[10, 1, 1, 10, 1, 1, 10]gives30.[0, 0, 0]gives0.
