Problem overview
The function rob receives an IntArray named nums, where nums[i] is the money in house i. Two neighbouring houses can't both be robbed, and the function returns the largest total you can take. The constraints are 1 to 100 houses with 0 to 400 in each.
For [2, 7, 9, 3, 1] the answer is 12, from houses 0, 2 and 4 (2 + 9 + 1). For [2, 1, 1, 2] the answer is 4, from the two ends. Robbing every other house gives only 3 here, whichever end you start from, so a fixed pattern of skipping exactly one house isn't enough. Sometimes the best plan skips two in a row.
Approach: decide house by house
Walk the street from left to right and keep the best total for the houses seen so far. At house i there are two choices:
- Skip it. The best total is whatever was best for the houses before it.
- Rob it. House
i - 1must stay untouched, so the money from houseiis added to the best total for the houses beforei - 1.
The better of the two is the best total up to house i. Each answer depends only on the previous two, so two running totals are enough: curr for the houses before the current one, and prev for the houses before that. Reusing earlier answers instead of trying every combination of houses is dynamic programming. Trying every subset of non-adjacent houses would take exponential time, while this takes one pass.
Here is the loop for [2, 7, 9, 3, 1], printing the values at each house:
i=0 house=2 prev=0 curr=0 best=2
i=1 house=7 prev=0 curr=2 best=7
i=2 house=9 prev=2 curr=7 best=11
i=3 house=3 prev=7 curr=11 best=11
i=4 house=1 prev=11 curr=11 best=12
end 12
At house 3 the best stays 11: robbing it would give 7 + 3 = 10, which is worse than skipping it. At house 4 the choice 11 + 1 = 12 wins.
Step by step
- Create
prevas avarequal to 0. Before the first house nothing has been robbed. - Create
curras avarequal to 0 for the same reason. - Loop
iover0 until nums.size. Every house is decided exactly once. - Compute
bestasmaxOf(curr, prev + nums[i]): skip the house, or rob it on top ofprev. - Move both totals one house to the right. Set
prevtocurrfirst, thencurrtobest. The opposite order would lose the oldcurr. - Return
curr. After the last house it is the best total for the whole street.
The solution in Kotlin
class Solution {
fun rob(nums: IntArray): Int {
var prev = 0
var curr = 0
for (i in 0 until nums.size) {
val best = maxOf(curr, prev + nums[i])
prev = curr
curr = best
}
return curr
}
}
The Kotlin details worth a look:
0 until nums.sizeis a range that excludes its upper end, soitakes the values 0 tonums.size - 1, the valid indices of anIntArray. Writing0..nums.sizewould includenums.sizeand throw anArrayIndexOutOfBoundsExceptionon the last round. Kotlin also offersnums.indicesfor the same range.maxOfis a standard-library function that returns the larger of its arguments, so no import is needed.IntArrayis a fixed-size array of primitiveintvalues on the JVM. It hassizeas a property, not alength()method, and it is indexed withnums[i].varversusval.prevandcurrchange in every round, so they arevar.bestis assigned once per round, so it is avaldeclared inside the loop.Intoverflow. The totals are at most 100 × 400 = 40,000, far below the 32-bit limit, so overflow isn't a concern here.
Complexity
Time: O(n), where n is the number of houses. The loop makes one pass with a constant amount of work per house.
Space: O(1). The function stores two totals, one temporary and the loop counter. A version with a table of best totals per house would use O(n).
Edge cases and common mistakes
- One house. For
[5]the loop runs once withprev = 0andcurr = 0, sobestis 5 and the function returns 5. - Two houses. For
[3, 10]the answer is 10. You can only take one of the two, and the larger wins. - All zeros.
[0, 0, 0]returns 0. - Taking every other house. This fails on
[2, 1, 1, 2], where both parities give 3 but the answer is 4. In[400, 1, 1, 400, 1]the answer is 800, from houses 0 and 3, which isn't a strict every-other pattern either. - Adding to
currinstead ofprev. The expressioncurr + nums[i]robs the house next to the last robbed one. On[1, 2, 3, 1]that sums every house and returns 7 instead of 4. - Wrong update order. Setting
curr = bestbeforeprev = currmakesprevequal tobestand drops the older total.
Testing
These inputs give the following results from the reference solution:
[1, 2, 3, 1]gives4.[2, 7, 9, 3, 1]gives12.[2, 1, 1, 2]gives4.[5]gives5.[3, 10]gives10.[0, 0, 0]gives0.[400, 1, 1, 400, 1]gives800.
