v9.1.1
Menu

House Robber II

mediumFREEDynamic ProgrammingBlind 75

Same as House Robber: each element of nums is the money in one house, and you cannot rob two adjacent houses. This time the houses are arranged in a circle, so the first and last houses are also adjacent. Implement rob_circular(nums) to return the maximum amount you can rob.

Example

Input
2,3,2
Output
3
Reasoning
  • nums lists the money in each house, in order around a circle: house 0 holds 22, house 1 holds 33, house 2 holds 22.
  • The usual rule applies: no two neighbouring houses may both be robbed. Because the street is a circle, house 2 also neighbours house 0, so with 3 houses every pair is adjacent.
  • That leaves only single-house choices: {0}→2\{0\} \to 2, {1}→3\{1\} \to 3, {2}→2\{2\} \to 2. Taking both ends would give 2+2=42 + 2 = 4, which would win on a straight street but is forbidden here.
  • The best total is max⁡(2,3,2)=3\max(2, 3, 2) = 3, so the output is 3.
  • Notice that the circle only changes the answer when the best straight-line plan uses both the first and the last house. For houses holding 1,2,3,11, 2, 3, 1, houses 0 and 2 are not neighbours, so 1+3=41 + 3 = 4 is still allowed.

Constraints

  • 1 <= len(nums) <= 100
  • 0 <= nums[i] <= 1000

Learn this in

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.