Python solution (divide into two parts).


  • 0
    C
    def rob(self, nums):
        if len(nums) == 1:
            return nums[0]
        return max(self.helper(nums[:-1]), self.helper(nums[1:]))
        
    def helper(self, nums):
        if not nums:
            return 0
        if len(nums) == 1:
            return nums[0]
        dp = [0] * len(nums)
        dp[0] = nums[0]
        dp[1] = max(nums[0:2])
        for i in xrange(2, len(nums)):
            dp[i] = max(dp[i-1], nums[i]+dp[i-2])
        return dp[-1]

  • 0
    C

    A version which uses less momery:

    def rob(self, nums):
        if not nums:
            return 0
        if len(nums) == 1:
            return nums[0]
        return max(self.helper(nums[:-1]), self.helper(nums[1:]))
        
    def helper(self, nums):
        if not nums:
            return 0
        if len(nums) == 1:
            return nums[0]
        a, b = nums[0], max(nums[:2])
        for i in xrange(2, len(nums)):
            a, b = b, max(b, a+nums[i])
        return b

Log in to reply
 

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