House Robber II

35 min · rob()

Closing the street into a circle turns its two safest-looking ends into neighbors.

The array nums lists the cash in houses arranged around a circle. You can't rob two adjacent houses, meaning neighboring positions on that circle. In particular, the first and last houses are adjacent. Return the largest total you can collect without choosing an adjacent pair.

You may skip any house, every amount is non-negative, and a single-house circle lets you take that one house.

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 1_000

Hints

Break the circle somewhere

A valid plan can never contain both the first and last houses. Split all plans into those that exclude the first and those that exclude the last.

Reuse the straight-street answer

Each split leaves one ordinary linear range. Solve 0..n-2 and 1..n-1, then keep the larger result.

Protect the one-house case

With one house, those two ranges would be empty or overlap awkwardly. Return its value before running either linear pass.

Follow-up

If the houses formed a branching neighborhood instead of one circle, what would a state need to remember about each house's parent?

Visible cases

Examples

Example 1

ready
Input
nums = [
  2,
  3,
  2
]
Expected
3
Why
the two 2s are neighbors around the circle, so take 3

Example 2

ready
Input
nums = [
  1,
  2,
  3,
  1
]
Expected
4
Why
houses 0 and 2 contribute 1 + 3

Example 3

ready
Input
nums = [
  1
]
Expected
1
Why
a one-house circle has no second house to conflict with

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite