Problem overview
The function rob receives a vector nums where nums[i] is the money in house i. Two neighboring houses can't both be robbed, and the function returns the largest total you can take.
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: houses 0 and 3. Taking every other house is not always best, since that choice gives only 3 here.
Approach: decide house by house
Trying every valid set of houses works, but the number of sets grows exponentially. A simpler view: walk along the street and, at each house, ask what the best total is for the houses up to and including this one. There are only two choices:
- Skip the house. The best total is the best for the houses before it.
- Rob the house. The previous house must stay untouched, so the money adds to the best total for the houses up to two before.
The larger of the two is the answer for this house. Each answer is built from two earlier answers, which is dynamic programming. Because only the last two answers are ever needed, two variables replace a table.
Take [2, 7, 9, 3, 1]. After each house, prev and curr hold:
house 2: prev=0 curr=2
house 7: prev=2 curr=7
house 9: prev=7 curr=11
house 3: prev=11 curr=11
house 1: prev=11 curr=12
The final curr, 12, is the answer.
Step by step
- Create
prevwithlet mut, set to 0. At the start of each round it is the best total for the houses up to two before the current one. Before the first house, nothing has been robbed. - Create
curr, also 0. It is the best total for the houses up to the one just before the current one. - Loop over the houses with
for i in 0..nums.len(). Each house is decided once, using only totals for the houses before it. - Compute
bestascurr.max(prev + nums[i]): skip the house and keepcurr, or rob it and add its money toprev. This one line is the whole algorithm. - Move both totals one house to the right:
prevbecomescurr, thencurrbecomesbest. Ifcurrwere assigned first,prevwould pick up the new value and the old one would be lost. - Return
currwith no semicolon. After the last house it is the best total for the whole street.
The solution in Rust
impl Solution {
fn rob(nums: Vec<i32>) -> i32 {
let mut prev = 0;
let mut curr = 0;
for i in 0..nums.len() {
let best = curr.max(prev + nums[i]);
prev = curr;
curr = best;
}
curr
}
}
The Rust details worth a closer look:
maxis a method.a.max(b)returns the larger of two values of the same type, herei32. The type ofcurris inferred fromnums[i], socurrandprevarei32without annotations.0..nums.len()is a range ofusizevalues, which is what indexing a vector requires. The upper end is excluded, soinever reachesnums.len().numsis owned. The function takes the vector by value, and indexing withnums[i]copies ani32out of it. Indexing out of bounds would panic, but the range makes that impossible here.mutonly where needed.prevandcurrchange in the loop, whilebestis assigned once per round with a plainlet.- The last expression.
currwithout a semicolon is the function's return value.
Complexity
Time: O(n), where n is the number of houses: one pass, with constant work per house.
Space: O(1). Only prev, curr and best are kept. The input vector is not counted.
Edge cases and common mistakes
- One house.
[5]returns 5:curr.max(prev + 5)is0.max(5). - An empty vector. The constraints rule it out, but the loop would simply not run and the function would return 0.
- Two houses.
[3, 10]returns 10: you rob one of them, the richer one. - Alternating houses. Robbing every other house fails on
[2, 1, 1, 2], where the best answer skips two houses in a row. The recurrence handles it, ascurrgoes 2, 2, 3, 4. - Adding to
currinstead ofprev.curr + nums[i]would rob a house next to the one just considered, which breaks the rule. - Zeros.
[0, 0, 0]returns 0. Money is never negative, so skipping a house never costs anything.
Testing
[1, 2, 3, 1]gives4.[2, 7, 9, 3, 1]gives12.[2, 1, 1, 2]gives4.[5]gives5.[3, 10]gives10.[4, 1, 1, 4, 1, 1, 4]gives12.[0, 0, 0]gives0.
