213. House Robber II

Description:

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

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.

 

Example 1:

Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
             because they are adjacent houses.

Example 2:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Sulotions:

class Solution:
    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])
        dp= dp2 = [0]*len(nums)
        older = nums[0]
        old = max(older, nums[1])
        # 不能同时抢第一家和最后一家
        answer1 = old
        for i in range(2, len(nums)-1):
            new = max(older + nums[i], old)
            answer1 = new
            older = old
            old = new
        older2 = nums[1]
        old2 = max(older2, nums[2])
        answer2 = old2
        for j in range(3, len(nums)):
            new2 = max(older2+ nums[j], old2)
            answer2 = new2
            older2 = old2
            old2 = new2
        return max(answer1, answer2)
posted @ 2018-06-26 23:27  谦曰盛  阅读(145)  评论(0编辑  收藏  举报