CodeArchon

medium1-D Dynamic ProgrammingAmazon

Circular Burglar Row

A cat burglar hits a round of neighboring houses (a ring); the first and last share an alarm wall.

Houses are arranged in a circle. Rob the maximum amount without hitting two adjacent houses; the first and last are adjacent.

Choose approach

2
0
?
1
?
2
i
1/5
Narrationstep 1 of 5

Chain 0..n-2: dp[0] = 2.

1def rob(nums):
2 n = len(nums)
3 if n == 1: return nums[0]
4 def line(lo, hi):
5 prev = cur = 0
6 for i in range(lo, hi + 1):
7 prev, cur = cur, max(cur, prev + nums[i])
8 return cur
9 return max(line(0, n - 2), line(1, n - 1))
Variables
phase=Chain 0..n-2
i=0
value=2

How to think about it

  1. Circular adjacency = can't take both first and last.
  2. Two linear DPs that exclude one endpoint each cover both cases.

Edge cases to catch in interview

  • Single house -> itself.
  • Two houses -> max of them.

Examples

Example 14
{"nums":[1,2,3,1]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed