My python solution

  • 0

    My solution, we can find the maximum when the number of houses are <= 3 by doing it manually, if the length is > 3, lets say 4, then we can find the answer by max( max(nums[0],nums[1]) , nums[0]+nums[2]) + nums[3], notice this step can be repeated over and over again, so I set nums[1] = max(nums[0],nums[1]), set nums[2] = nums[0]+nums[2] and pop nums[0] which shorten the length by 1.

    We will do this until the length is equal to 3 and we can find the answer again manually.

    class Solution(object):
        def rob(self, nums):
            :type nums: List[int]
            :rtype: int
            if len(nums) == 0:
                return 0
            if len(nums) == 1:
                return nums[0]
            if len(nums) == 2:
                return max(nums[0], nums[1])
            while len(nums) > 3:
                nums[1] = max(nums[0], nums[1])
                nums[2] += nums[0]
            return max(nums[0]+nums[2], nums[1])

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.