Start learning free

LESSON 523 OF 671 · DYNAMIC PROGRAMMING

House Robber II

Practice O(n)

You get an array nums, the money in each house. House i holds nums[i].

Return the most money you can rob.

Houses next to each other share an alarm. So you can never rob two neighbors.

This time the houses stand in a circle. The last house is next to house 0. So the first and the last house can't both be robbed.

Example 1:

Input: nums = [5, 1, 1, 5]
Output: 6
Explanation: Houses 0 and 3 hold 5 each.
In the circle, they are neighbors.
So the best is one 5 and one 1.
For example, houses 0 and 2 give 5 + 1 = 6.

Example 2:

Input: nums = [3, 8, 2, 4, 9]
Output: 17
Explanation: Rob house 1 (8) and house 4 (9).
That gives 8 + 9 = 17.
They are not neighbors, even in the circle.

Example 3:

Input: nums = [7]
Output: 7
Explanation: With one house, rob it.

Constraints:

  • 1 to 100 houses.
  • Each house holds from 0 to 1,000.

Note:

Your algorithm should run in O(n) time, where n is the number of houses.

STEP 1 OF 12
    Ctrl + Enter to check