progress

~/problems / 1-D dynamic programming / Intro DP

House Robber

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

A street has a row of houses, and nums[i] is the cash in house i. You may take the cash from any set of houses as long as no two chosen houses are next to each other. Return the largest total you can collect.

Implement rob(nums: list[int]) -> int.

rob([2, 7, 9, 3, 1])  # 12  (2 + 9 + 1)
rob([6, 1, 1, 6])     # 12  (6 + 6: skipping two in a row is allowed)
rob([])               # 0

Constraints: 0 <= len(nums) <= 10^5, 0 <= nums[i] <= 10^4.

⭐ Bonus: a speed test with 100,000 houses earns a star in O(n) time. Trying every subset is exponential and won't finish.

Show hint

For the best total over the first i houses, house i is either taken or skipped, and each choice leaves a smaller version of the same question.

Topic: Intro DP. State, transition, base case; top-down memo vs bottom-up table.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc