CodingNodes / 1-D Dynamic Programming / House Robber II System design Space play · ←→ step · R restart

Problem

Houses stand in a circle, and nums[i] is the cash inside house i. The first and last houses are neighbours. Robbing two neighbouring houses sounds the alarm.

Return the largest total cash you can take without setting off the alarm.

Constraints

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

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Two passes of the House Robber recurrence, each over n - 1 houses.

Space: Each pass builds a dp array of about n slots.

The first and last house cannot both be robbed, so break the circle two ways: drop the last house, or drop the first. Each is an ordinary row of houses, solved with dp[i] = max(dp[i-1], dp[i-2] + cash). The answer is the larger of the two.