Skip to content

198. House Robber

Medium LeetCode

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.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Example 1

Input: nums = [1,2,3,1]

Output: 4

Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.

Example 2

Input: nums = [2,7,9,3,1]

Output: 12

Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

How to solve the problem

  • Recursion with Memoization
python
class Solution:
    def rob(self, nums: List[int]) -> int:
        cache = [-1] * len(nums)  # Use cache to store the value we already calculated

        def dfs(i):
            if i < 0:
                return 0
            if cache[i] != -1:
                return cache[i]
            result = max(dfs(i - 1), dfs(i - 2) + nums[i])
            cache[i] = result
            return result

        return dfs(len(nums) - 1)
  • Dynamic Programming
python
class Solution:
    def rob(self, nums: List[int]) -> int:
        f = [0] * (len(nums) + 2) 
        for i in range(len(nums)):
            f[i + 2] = max(f[i + 1], f[i] + nums[i]) # State transition equation
        return f[len(nums) + 1]
  • Optimized Dynamic Programming
python
class Solution:
    def rob(self, nums: List[int]) -> int:
        f0 = f1 = 0  # f0: two houses ago; f1: previous house
        for num in nums:
            new_f = max(f1, f0 + num)  # Rob or skip current house
            f0, f1 = f1, new_f         # Move window forward
        return f1  # Max money after considering all houses

Complexity

  • Approach 1 (Recursion with Memoization): Time complexity: O(n), Space complexity: O(n)
  • Approach 2 (Dynamic Programming): Time complexity: O(n), Space complexity: O(n)
  • Approach 3 (Optimized DP): Time complexity: O(n), Space complexity: O(1)

Comments

No comments yet. Be the first to comment!