House Robber II — LeetCode 213 Python Solution

MediumArrayDynamic Programming
Problem
#213
Reading time
2 min

The problem

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed.

Example

Input
nums = [2,3,2]
Output
3
Explanation
You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.

Python solution

Python
class Solution:
    def rob(self, nums: List[int]) -> int:
        def _rob(nums):
            f = g = 0
            for x in nums:
                f, g = max(f, g), f + x
            return max(f, g)

        if len(nums) == 1:
            return nums[0]
        return max(_rob(nums[1:]), _rob(nums[:-1]))

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 213. House Robber II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75 and NeetCode 150.

Frequently asked questions

How hard is LeetCode 213. House Robber II?
LeetCode 213. House Robber II is rated Medium on LeetCode.
What is the time complexity of LeetCode 213. House Robber II?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 213. House Robber II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 213. House Robber II cover?
LeetCode 213. House Robber II is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview