Problem overview
The method rob receives an array nums, where nums[i] is the money in house i. Two neighbouring houses share a security system, so robbing both on the same night is not allowed. The method returns the most money you can take without robbing two adjacent houses. The constraints are 1 to 100 houses, each holding 0 to 400.
For [1, 2, 3, 1] the answer is 4: houses 0 and 2 give 1 + 3. For [2, 7, 9, 3, 1] it is 12 (houses 0, 2 and 4: 2 + 9 + 1). For [2, 1, 1, 2] it is 4, taking the first and last houses. Robbing every other house would give only 3 there, so a fixed pattern isn't enough: the choice depends on the amounts.
Approach: decide house by house
Walk along the street from left to right. At house i there are two options:
- Skip it. The best total is then whatever was best for the houses before it.
- Rob it. Then house
i - 1must stay untouched, so you addnums[i]to the best total for the houses up toi - 2.
The better of the two is the best total up to house i. This is dynamic programming: each answer is built from answers for shorter streets, and each of those is computed once.
The choice at house i only looks at the two previous answers, so two variables are enough instead of an array. curr is the best total for the houses before house i, and prev is the best total for the houses before house i - 1. Both start at 0, because before the first house nothing has been robbed.
The table below follows [2, 7, 9, 3, 1] and comes from a real run. The columns show the values after each 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 i = 2, prev + nums[i] is 2 + 9 = 11, which beats skipping the house (7). At i = 3, robbing would give 7 + 3 = 10, less than 11, so the house is skipped. The final curr is 12.
Step by step
- Create
prevwithvar, set to 0. It is the best total two houses back from the current one. It is avarbecause the loop changes it. - Create
currthe same way, also 0. It is the best total up to the house just before the current one. - Loop over every house.
igoes over the half-open range0..<nums.count. Write the closing brace right away. - Compute
bestwithlet. It ismax(curr, prev + nums[i]): skip the house, or rob it on top ofprev. - Move both totals one house to the right. Set
prevtocurrfirst, thencurrtobest. In the other order,prevwould copy the new value and lose the old one. - Return
currafter the loop. It is the best total for the whole street.
The solution in Swift
class Solution {
func rob(_ nums: [Int]) -> Int {
var prev = 0
var curr = 0
for i in 0..<nums.count {
let best = max(curr, prev + nums[i])
prev = curr
curr = best
}
return curr
}
}
The Swift details worth a closer look:
0..<nums.count. The half-open range stops beforecount, so the last index iscount - 1. For an empty array it is the empty range0..<0, so the loop is skipped and the method returns 0. The constraints promise at least one house, but the code handles an empty street too.maxis a global function.max(curr, prev + nums[i])works on any two values of the same comparable type, here twoInts.letversusvar.bestis created fresh in every round and never changes, so it is alet.prevandcurrare assigned in the loop, so they arevars.- Safe indexing. Reading
nums[i]outside the array stops the program with a run-time error, but the range guarantees thatiis always valid. - Overflow traps.
Intis 64 bits and overflow crashes instead of wrapping. With at most 100 houses of at most 400, the total is at most 40,000, so it is never close.
Complexity
Time: O(n), where n is the number of houses. The loop visits each house once and does constant work.
Space: O(1). The method stores only prev, curr and best.
Edge cases and common mistakes
- One house.
[5]returns 5:max(0, 0 + 5). - Two houses.
[3, 4]returns 4. You can take only one, so the larger. - Zeros.
[0, 0]returns 0. - Greedy by position. Taking every other house fails on
[2, 1, 1, 2], where the answer is 4 and robbing houses 0 and 2 gives only 3. - Greedy by amount. Taking the biggest house first and then what remains can block better pairs. Comparing the two options at every house avoids this.
- Using
curr + nums[i]. That adds the money of houseito a total that may include housei - 1, which breaks the rule. - Wrong update order. Setting
curr = bestbeforeprev = currleaves both variables equal.
Testing
Results from running the reference solution:
[1, 2, 3, 1]gives4.[2, 7, 9, 3, 1]gives12.[2, 1, 1, 2]gives4.[5]gives5.[3, 4]gives4.[400, 1, 1, 400]gives800.
