House Robber — LeetCode 198 Python Solution

MediumArrayDynamic Programming
Problem
#198
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, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Example

Input
nums = [1,2,3,1]
Output
4
Explanation
Rob house 1 (money = 1) and then rob house 3 (money = 3).

Python solution

Python
class Solution:
    def rob(self, nums: List[int]) -> int:
        @cache
        def dfs(i: int) -> int:
            if i >= len(nums):
                return 0
            return max(nums[i] + dfs(i + 2), dfs(i + 1))

        return dfs(0)

Complexity

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

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 198. House Robber 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, NeetCode 150, LeetCode 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 198. House Robber?
LeetCode 198. House Robber is rated Medium on LeetCode.
What is the time complexity of LeetCode 198. House Robber?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 198. House Robber?
The Python solution on this page uses O(n), where n is the length of the array auxiliary space.
What topics does LeetCode 198. House Robber cover?
LeetCode 198. House Robber 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