Practice · Dynamic programming (1D) · 6 of 8

Rob Houses in a Circle

Houses stand in a circle, and nums[i] is the money in house i. House i is next to houses i − 1 and i + 1, and the last house is next to the first. Robbing two neighbouring houses sets off an alarm.

Return the largest total you can take without robbing two neighbours. When there is only one house, you can rob it.

Example 1

Input
nums = [2, 3, 2]
Output
3
Houses 0 and 2 are neighbours in the circle, so the best is house 1 on its own.

Example 2

Input
nums = [1, 2, 3, 1]
Output
4
Rob houses 0 and 2: 1 + 3 = 4.

Constraints

  • nums holds 1 to 2000 numbers.
  • 0 ≤ nums[i] ≤ 1000