Leetcode: House Robber II

Question

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Show Tags
Show Similar Problems

Solution

Analysis

Get idea from here.

Code

class Solution(object):
    def rob(self, nums):
        """ :type nums: List[int] :rtype: int """

        if nums==[]:
            return 0
        if len(nums)<=2:
            return max(nums)

        return max( self.helper(nums, 0, len(nums)-2), self.helper(nums, 1, len(nums)-1) )

    def helper(self, nums, s, e):
        temp1 = 0
        temp2 = nums[s]
        for ind in range(s+1, e+1):
            res = max( temp1 + nums[ind], temp2 )
            temp1 = temp2
            temp2 = res

        return res        

Error Path

    1.
 for ind in range(s+1, e+1):
            res = max( temp1 + nums[ind], temp2 )
            temp1 = temp2
            temp2 = res

made a mistake on start and stop condition of loop

Take home message

For dynamic programming, we can save the storage complexity for some specific problem.

你可能感兴趣的:(Leetcode: House Robber II)