Problem overview
The method rob receives an array nums where nums(i) is the money in house i. Robbing two neighboring houses on the same night triggers an alarm, so no two chosen houses may be next to each other. The method returns the largest total you can take.
For [1, 2, 3, 1] the best choice is houses 0 and 2, which gives 1 + 3 = 4. For [2, 7, 9, 3, 1] it is houses 0, 2 and 4: 2 + 9 + 1 = 12. The constraints give between 1 and 100 houses with 0 to 400 in each.
Approach: decide house by house
Trying every allowed set of houses works only for tiny streets, since the number of sets doubles with each house. Instead, walk from left to right and keep the best total for the houses seen so far.
When you reach house i, you have two options:
- Skip it. The best total is then the best for the houses before it, which is
curr. - Rob it. House
i - 1must stay untouched, so the money from houseiadds to the best total for the houses up toi - 2, which isprev + nums(i).
The larger of the two is the best total up to house i. That choice is the whole algorithm. Each answer uses only the previous two, so two variables replace a whole table of answers.
Taking every other house is not always optimal. For [2, 1, 1, 2] the even-indexed houses give 2 + 1 = 3 and the odd-indexed ones give 1 + 2 = 3, but robbing houses 0 and 3 gives 4.
Step by step
- Create
prevwithvar, starting at 0. It is the best total for the houses up to two before the current one. Before any house, nothing has been robbed. - Create
currthe same way, starting at 0. It is the best total for the houses up to the one just before the current one. - Loop
iover0 until nums.length. Every house is decided once. - Compute
bestwithmath.max. It is the larger ofcurr(skip) andprev + nums(i)(rob), stored in aval. - Move both totals one house to the right. Set
prevtocurr, thencurrtobest. Doing it in the other order would overwrite the valueprevneeds. - End with
curr. After the last house it is the best total for the whole street.
Here is the loop on [2, 1, 1, 2]:
i=0 best=2 prev=0 curr=2
i=1 best=2 prev=2 curr=2
i=2 best=3 prev=2 curr=3
i=3 best=4 prev=3 curr=4
At i = 1 skipping wins (2 against 0 + 1). At i = 3 robbing wins: prev + nums(3) is 2 + 2 = 4, while skipping would keep 3.
The solution in Scala
class Solution {
def rob(nums: Array[Int]): Int = {
var prev = 0
var curr = 0
for (i <- 0 until nums.length) {
val best = math.max(curr, prev + nums(i))
prev = curr
curr = best
}
curr
}
}
The Scala details worth a closer look:
- Arrays use parentheses. Scala reads element
iasnums(i), notnums[i]. Square brackets inArray[Int]are for types. untilexcludes its end.0 until nums.lengthvisits indices 0 tolength - 1, exactly the valid ones. Writing0 to nums.lengthwould read one element past the end and throw anArrayIndexOutOfBoundsException.math.max. It is the standard way to take the larger of two numbers, here twoIntvalues.- The last expression is the result. The final
curris the return value, with noreturnkeyword.
Complexity
Time: O(n), where n is the number of houses. Each house is handled once with a constant amount of work.
Space: O(1). The method keeps prev, curr, best and the loop index, and never copies the array.
Edge cases and common mistakes
- One house. For
[5],bestismax(0, 0 + 5)= 5. The starting zeros make this case need no special code. - Two houses. For
[1, 2]the method returns 2: you can take only one of the neighbors, and the larger is better. - Zeros.
[0, 0]returns 0. Since money is never negative, robbing never lowers a total. - Greedy by alternating. Always taking houses 0, 2, 4 and so on fails on
[2, 1, 1, 2], as shown above. Another case is[100, 1, 1, 100], which returns 200 by taking the two ends. - Updating in the wrong order. If
currchanges beforeprevis set,prevandcurrend up equal and the next round adds the wrong value. - Empty input. The constraints promise at least one house, but an empty array would return 0, because the loop does not run.
Testing
[1, 2, 3, 1]gives 4.[2, 7, 9, 3, 1]gives 12.[2, 1, 1, 2]gives 4.[100, 1, 1, 100]gives 200.[3, 10, 3, 1, 2]gives 12.[5]gives 5.[0, 0]gives 0.
