MediumNo. 0198

House Robber — LeetCode 198 Python Solution

Topics
Array, Dynamic Programming
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)where n is the length of the array

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

Related problems
No.ProblemDifficulty
0213House Robber IIMedium
0337House Robber IIIMedium
2560House Robber IVMedium
0188Best Time to Buy and Sell Stock IVHard
0045Jump Game IIMedium
0053Maximum SubarrayMedium

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.

Free to download. Check it runs on your machine, then pick a plan.