Houses stand in a ring, and nums[i] is the cash inside house i. Because it is a ring, the first house and the last house are next to each other.
A thief may rob any set of houses, but never two that are next to each other, or an alarm goes off. Return the most cash the thief can take.
Example 1
Input: nums = [6, 2, 3, 5] Output: 9 Why: 6 + 5 is not allowed (they touch), so 6 + 3 = 9
2 more examples and the constraints
Example 2
Input: nums = [4] Output: 4 Why: one house has no neighbour to worry about
Example 3
Input: nums = [5, 1, 1, 5] Output: 6 Why: the two 5s are neighbours around the ring, so 5 + 1 = 6
Constraints
- 1 ≤ length of nums ≤ 100
- 0 ≤ nums[i] ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(n)
- Two passes, two variablesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 houses | Verdict |
|---|---|---|---|
| Recursion with a memo | O(n) | Passes; easy to derive | |
| Two passes, two variables | O(n) | Best; no memo, no recursion |
n = number of houses. Plain recursion without a memo would be O(2ⁿ).
Edge cases to test
- One house. [4] returns 4; both passes would be empty.
- Two houses. [3, 8] are neighbours both ways, so take the larger: 8.
- Rich first and last. [9, 1, 1, 9, 1]: the two 9s are not neighbours here, so 18 is fine.
- Empty houses. [0, 0, 0] returns 0.
Common mistakes
- Solving it as a straight street, which can rob both the first and the last house.
- Forgetting the one-house case, so both passes run on an empty range and return 0.
- Updating prev before using it, so cur is computed from the wrong house.
How to talk through it
- 1Clarify. Is the first house really next to the last? Can there be one house? Can a house be empty?
- 2Recall the straight street. For a line, best = max(skip this house, rob it plus the best two back).
- 3Break the circle. The first and last cannot both be robbed, so solve the street without each and take the max.
- 4Code it with two variables. Write a helper for one street and call it twice.
- 5Test out loud. Run one house, two houses, and a case where the ends are the richest.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?