4.28python Leetcode 213

213House Robber II

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.


题解:

环形数组,每次只能取不相邻的2个数,求最大和。

动态规划问题。

对于从2开始的每一个房间i,到这个房间为止能偷到的最多的钱

max_money[i] = max( max_money[i-1], max_money[i-1] + nums[i] )

当然,因为是环形数组,因此要考虑第一第二个房间和最后一个房间的关系。

我这里是直接进行了2次dp,第一次考虑如果只取第一个房间的钱,舍弃第二个房间和最后一个房间的钱。

第二次是不取第一个房间的钱,其他正常取。这样就可以覆盖全部的情况了。



class Solution(object):
    def rob(self, nums):
        if nums:
            if(len(nums) == 1):
                return nums[0]
            
            max_money1 = [0 for i in range(len(nums))]
            max_money2 = [0 for i in range(len(nums))]
            max_money1[0] = nums[0]
            max_money1[1] = nums[0]
            max_money2[0] = 0
            max_money2[1] = nums[1]
            
            i = 2
            while i < len(nums) -1:
                max_money1[i] = max(max_money1[i-1], max_money1[i-2] + nums[i])
                i = i+1
            i = 2
            while i < len(nums):
                max_money2[i] = max(max_money2[i-1], max_money2[i-2] + nums[i])
                i = i +1
            
            return max(max_money1[-2], max_money2[-1])
        else:
            return 0
        
        """
        :type nums: List[int]
        :rtype: int
        """


猜你喜欢

转载自blog.csdn.net/control_xu/article/details/80213851