Question 198 House Robber

Link:

https://leetcode.com/problems/house-robber/

My Code:

class Solution:
    def rob(self, nums: List[int]) -> int:
        if len(nums) ==1:
            return nums[0]
        elif len(nums) ==2:
            return max(nums[0],nums[1])
        elif len(nums) ==3:
            return max(nums[0]+ nums[2], nums[1])
        else:
            Index = 3
            MaxList = [0]* (len(nums)+3)
            while Index < len(nums)+3:
                if nums[Index-3] ==0:
                    MaxList[Index] = max(MaxList[Index-1],MaxList[Index-2])
                    if Index == len(nums)+2 :
                        break
                    else:
                        Index+=1
                        MaxList[Index] = MaxList[Index-1]+nums[Index-3]
                else:
                    MaxList[Index] = max(MaxList[Index-2],MaxList[Index-3])+nums[Index-3]
                Index +=1
        return max(MaxList[len(MaxList)-1], MaxList[len(MaxList)-2])

Explanation: Two issues: if there is an zero in the list, there is definitely no need to rob that house, as that would eliminates the opportunities to rob the house next to it with no extra benefit. So the evaluate the list for the 0 zero value house as the maximum between the house one block before it and the house two blocks before it. We do not take the third house as if we choose to rob the three houses before the house we are facing now, it does no damage to rob the house one house before the house we are facing now, as the value is non negative. Similar for the situation when the value for the house is not zero. We just need to take the max between the house two blocks before it and three blocks before it, then add the value of the house we are facing now. So we just keep the calculation and take the maximum between the last one and the second last one in the list.

Leave a comment