House Robber II

Medium1-D dynamic programming

Houses stand in a circle, so the first house and the last house are next to each other. nums[i] is the cash in house i. A thief can take the cash from any houses he likes, but never from two neighbouring houses: that sets off the alarm.

Return the most cash he can take.

Examples

Example 1
Input:  nums = [4, 2, 5]
Output: 5

In a circle of three, every house is next to the other two, so only one can be taken.

Example 2
Input:  nums = [3, 6, 2, 8]
Output: 14

Take 6 and 8: they are not neighbours, even in the circle.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 1000

Stuck?

Hint 1

The circle only adds one rule: the first and the last house cannot both be taken. So at least one of them is left out.

Hint 2

Solve the straight row twice, once without the last house and once without the first, and return the larger total. Watch out for a single house.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur