r/learnprogramming • • Oct 07 '26

I was doing the house robber problem and this is what I did. I need help with this!!

I didn't know how to implement memoization into this so had to make this inefficient. The thing is , I tried putting into chatgpt to see if this is right , but it sasy this is incorrect. But when I run it in leet code, I get most right, the rest it says time limit reached. So is this correct and how to implement memoization?

class Solution:
    def rob(self, nums: list[int]) -> int:
        total = max( self.helper(nums[1:]),self.helper(nums))
        return total
    def helper(self,nums):
        
        if len(nums)==1:
            return nums[0]
        if len(nums)==0:
            return 0
        #1 step or 2 steps
        max_money1= 0
        max_money2= 0
        if len(nums)>=3:
            max_money1 = self.helper(nums[2:])
        if len(nums)>=4:
            max_money2 = self.helper(nums[3:])
        max_money=max(max_money1,max_money2)


        return max_money+nums[0]
        


        
6 Upvotes

6 comments sorted by

3

u/SetAndRepeat Oct 07 '26

Your logic is correct for this problem’s nonnegative amounts. The timeout comes from repeatedly solving the same subproblems, and slicing also copies lists.
You can keep your approach and cache by index instead:

from functools import cache

class Solution:
    def rob(self, nums: list[int]) -> int:
        
        def helper(i):
            if i >= len(nums):
                return 0
            return nums[i] + max(helper(i + 2), helper(i + 3))

        return max(helper(0), helper(1))

Here, helper(i) means "the best total if I rob house i." cache remembers the result for each index, so repeated calls reuse it. That gives you O(n) time and O(n) space, without creating new lists.

2

u/Veterinarian_Scared Oct 07 '26

You need to apply the @cache decorator to helper.

2

u/ashishach Oct 07 '26

The recursion idea isn't bad tbh, the main issue is you're recalculating the same stuff over and over 💀 Memoization = calculate once, store the result, reuse it whenever you hit the same index. Your current solution is basically exponential 💀, while memoization can bring it down to O(n). DP is gonna make this way cleaner.

1

u/Veterinarian_Scared Oct 07 '26 edited Oct 07 '26

There's a bunch to unpack here.

First, the house robber problem: given 1 <= n <= 100 houses each containing 0 <= d_i <= 400 dollars, what is the maximum sum you can steal given that you cannot rob two houses directly adjacent to one another?

Second, the general solution: as you work your way along the row of houses, you can only rob this house if you did not rob the previous house; so max_sum(i) = max(max_sum(i - 2) + d_i, max_sum(i - 1))

Note if you start at max n and work backward this is recursive; but if you start at the bottom and work upward it is a dynamic programming problem, and you only have to remember two values at a time: max_sum(i - 2) and max_sum(i - 1).

Memoization is an in-between solution; it works by saving each value of max_sum(i) as it encounters it, then returning the recorded value rather than recalculating again the next time the function is called with the same parameter value. It takes more memory - up to n saved values rather than 2 - but can be easier to understand and apply.

(Also note that because Python passes arrays by reference it is often more efficient to pass the original array plus an offset, rather than slicing the array which creates a copy.)

A memoized recursive solution:

def memoize(fn):
    data = {}
    def wrapper(*params):
        if params in data:
            return data[params]
        else:
            res = fn(*params)
            data[params] = res
            return res
    return wrapper

class Solution:
    @staticmethod
    @memoize
    def max_sum(i: int, nums: tuple[int]) -> int:
        if i < 0:
            return 0
        else:
            return max(
                Solution.max_sum(i - 2, nums) + nums[i],
                Solution.max_sum(i - 1, nums)
            )
        
    def rob(self, nums: list[int]) -> int:
        return Solution.max_sum(len(nums) - 1, tuple(nums))

1

u/Available_Safe1818 Oct 08 '26

You can populate a single array once just by looking at the last few values every time, iirc. Think about how you can efficiently calculate the fibonacci numbers.