LeetCode in Python 213. House 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.

Differs from the first question is that the annular array, the first and last are not simultaneously stolen. In fact, the first question is to rob twice, rob (start, end) represent from start to end to be able to steal a maximum of attention does not necessarily include end, but it must include a start; visible house robber i do not have the whole array initial dp , requires only two variables oneBefore and twoBefore, represent the end = i-1 end = i-2 at the maximum and, when the update can traverse.

Solution class (Object): 
    DEF Rob (Self, nums): 
        "" " 
        : nums of the type: List [int] 
        : rtype: int 
        " "" 
        IF not nums: return 0 
        IF len (nums) == 1: return nums [ 0] 
        
        DEF robFrom (begin, end): 
            # begin to return from the maximum end to end may be stolen or may not include end 
            oneBefore = twoBefore = RES = 0 
            for I in Range (begin, end): 
                TEMP = max (oneBefore , the nums [I] + twoBefore) 
                twoBefore = oneBefore 
                oneBefore = TEMP 

            return oneBefore 

        return max (robFrom (0, len (the nums) -1), robFrom (. 1, len (the nums)))

Guess you like

Origin www.cnblogs.com/lowkeysingsing/p/11279533.html