CodeArchon

medium1-D Dynamic ProgrammingLinkedInAmazon

Burglar Row Planner

A cat burglar picks a non-adjacent subset of houses on one street to maximize total loot without triggering alarms between neighbors.

Given an array of non-negative integers representing money in each house, return the max you can rob without taking from two adjacent houses.

Choose approach

2
0
7
1
?
2
?
3
?
4
i
1/5
Narrationstep 1 of 5

Base dp[0], dp[1].

1def rob(nums):
2 n = len(nums)
3 if n == 0: return 0
4 if n == 1: return nums[0]
5 dp = [0]*n
6 dp[0] = nums[0]; dp[1] = max(nums[0], nums[1])
7 for i in range(2, n):
8 dp[i] = max(dp[i-1], dp[i-2] + nums[i])
9 return dp[-1]
Variables

How to think about it

  1. Two choices at each house.
  2. Rolling two scalars gives O(1) space.

Edge cases to catch in interview

  • Empty -> 0.
  • One house -> that value.

Examples

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

Try your own input

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