Skip to main content
CodeOath
← All problems

Problem

House Robber II

Medium
  • dynamic-programming

This is House Robber with one change: the houses stand in a ring, so the last house is a neighbour of the first. nums[i] is the cash in house i. You can rob any set of houses as long as no two of them are neighbours. Return the largest total you can take.

Example 1
Input
nums = [5, 1, 1, 5]
Output
6
Explanation

the two 5s are houses 0 and 3, which touch around the ring, so only one of them can be robbed. Pairing it with a 1 that is not next to it gives 5 + 1 = 6.

Example 2
Input
nums = [4, 1, 6, 2, 9]
Output
15
Explanation

houses 2 and 4 are not neighbours, so 6 + 9 = 15. Adding house 0 would make 19, but house 0 touches house 4 around the ring.

Example 3
Input
nums = [7]
Output
7
Explanation

with one house there is no other house to conflict with, so you rob it.

Constraints:

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

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.