Example 1
- Input
- nums = [2, 3, 2]
- Output
- 3
Houses 1 and 3 are adjacent around the circle, so rob house 2 alone for 3.
Given cash in houses arranged in a circle, rob the largest total possible where both adjacent houses and the first-last pair cannot be robbed together.
You are given an integer array nums where nums[i] is the money in house i, and the houses form a circle: house 0 and house n - 1 are adjacent. Robbing two adjacent houses triggers the alarm.
Return the maximum money robbable with no two robbed houses adjacent around the circle. With a single house, its value is the answer.
1 <= nums.length <= 1000 <= nums[i] <= 1000Houses 1 and 3 are adjacent around the circle, so rob house 2 alone for 3.
Rob house 1 (money 1) and house 3 (money 3) for a total of 4.
Robbing house 3 alone for 3 beats every pair, since houses 1 and 3 are now neighbours.
A single house is not a conflicting pair with itself. Rob it for 7; removing either endpoint would incorrectly leave an empty line.
The circle adds one conflict: the first and last houses are neighbours. In Example 1, [2, 3, 2], taking both endpoint values would give 4 but trigger the alarm. Every valid plan leaves at least one endpoint unrobbed. Solve the line without the last house and the line without the first, then keep the richer answer. Within either line, each house is a choice between skipping it and taking it with the best plan that ends two houses earlier.
Reveal Recursive Take Or Skip: intuition, complexity, and code
0 and n - 1 are neighbours.0 first and solve the remaining line both ways.0..n-2 and on 1..n-1, then keep the richer run.0 from either run without special handling.[2, 3, 2].0 instead of the house value.Break a circular adjacency ban by branching on one member of the wrapped pair; each branch is a line problem solvable with the same rolling recurrence.