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. Tags: Dynamic Programming

Try It!

Discussion

Video

Solution

class Solution:
    def rob(self, nums: List[int]) -> int:
        if len(nums) == 0:
            return 0
        if len(nums) == 1:
            return nums[0]
        
        dp_normal = [0 for i in range(len(nums))]
        dp_round = [0 for i in range(len(nums))]
        
        dp_normal[0] = nums[0]
        dp_normal[1] = max(nums[0], nums[1])
        
        dp_round[1] = nums[1]
        
        for i in range(2, len(nums)):
            dp_normal[i] = max(dp_normal[i - 1], dp_normal[i - 2] + nums[i])
            dp_round[i] = max(dp_round[i - 1], dp_round[i - 2]  + nums[i])
        
        return max(dp_normal[len(nums) - 2], dp_round[len(nums) - 1])