Example 1
- Input
- nums = [1, 2, 3, 1]
- Output
- 4
Rob house 1 (money 1) and house 3 (money 3) for a total of 4.
Given the cash in each house on a street, rob the largest total possible without ever robbing two adjacent houses.
You are given an integer array nums where nums[i] is the money in house i. Robbing two adjacent houses in one night triggers the alarm.
Return the maximum money robbable with no two robbed houses adjacent. Every house may also be skipped, and all amounts are non-negative.
1 <= nums.length <= 1000 <= nums[i] <= 400Rob house 1 (money 1) and house 3 (money 3) for a total of 4.
Rob houses 1, 3, and 5 for 2 + 9 + 1 = 12.
The only house contains no money. Robbing it or skipping it both give 0, so the answer is 0.
Take indices 0 and 3 for 4. They are not adjacent on a line; fixed even-index and odd-index plans each give only 3, so choosing a parity is not sufficient.
The largest individual house does not decide the best night: neighbouring choices affect what remains available. In Example 1, [1, 2, 3, 1], taking values 1 and 3 gives 4, beating the middle value 2. At each position compare skipping this house with taking it plus the best plan that excludes its neighbour. Only the best totals through the previous two positions matter, so a whole table can be compressed into two running totals.
Reveal Recursive Take Or Skip: intuition, complexity, and code
best(i - 1) and best(i - 2) feed the next house, so two rolling variables replace the array.0; skipping everything stays valid and optimal.[2, 1, 1, 2], where the optimum mixes parities for 4.nums[i] + prev1 for the rob branch reuses the previous house and can rob neighbours.prev2 after overwriting prev1 feeds the new value into both slots; shift with a temporary.Take-or-skip optimisation over a line, where taking blocks the neighbour, is a two-state rolling recurrence: the best ending before contains everything the future needs.