704. Ring Road Burglar
The houses of a small village stand around a circular road, listed in order as houses, where houses[i] is the loot in house i. A thief may choose any set of houses, but two neighbouring houses cannot both be chosen. Because the road is a ring, the last house is also next to the first one, so houses 0 and n-1 cannot be chosen together.
Return the largest total loot the thief can collect. A village with a single house simply gives that house's loot.
Aim for time O(n) and extra space O(1).
Example 1
- Input:
- houses = [4,9,3,7]
- Output:
- 16
- Explanation:
Houses 0 and 3 touch on the ring, so the best choice is houses 1 and 3 for 9 + 7 = 16.
Example 2
- Input:
- houses = [5,8,6,2,7]
- Output:
- 15
- Explanation:
Taking houses 1 and 4 gives 8 + 7 = 15; houses 0 and 4 are neighbours on the ring, so 5 + 6 + 7 is not allowed.
Constraints
1 ≤ n = houses.length ≤ 105
0 ≤ houses[i] ≤ 1000
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(n)
- Space
- O(1)