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
        """


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章