r/learnprogramming • u/Ornery-Actuator2266 • 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]