House Robber II

Question

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.

Tags

  • Array
  • Dynamic Programming

Thought

Use the same idea as the previous problem, but we need to consider two different conditions and take the maximum one from these two conditions.

Code

class Solution(object):
    def helper(self, wealths):
        print wealths
        dp = [0 for _ in xrange(1 + len(wealths))]
        dp[0] = 0
        dp[1] = wealths[0]
        for i in xrange(1, len(wealths)):
            num = wealths[i]
            dp[i + 1] = max(dp[i], dp[i - 1] + num)
        print "dp: ", dp
        return dp[-1]


    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        print nums
        if nums == []:
            return 0
        if len(nums) == 1:
            return nums[0]
        max1 = self.helper([0] + nums[1:])
        max2 = self.helper(nums[:-1] + [0])
        return max(max1, max2)

results matching ""

    No results matching ""