Leetcode 213, House Robber II

 

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

 

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.

 

 

本题和House Robber差不多,分成两种情况来解决。第一家是不是偷了,如果偷了,那么最后一家肯定不能偷。

 

 1 class Solution(object):
 2     def rob(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         if not nums:
 8             return 0
 9         n = len(nums)
10         if n == 1:
11             return nums[0]
12         if n == 2:
13             return max(nums[0], nums[1])
14             
15         dp = [0]* n
16         dp[0] = 0
17         dp[1] = nums[1]
18         
19         for i in range(2,n):
20             dp[i] = max(dp[i-2]+nums[i], dp[i-1])
21         
22         case1 = dp[-1]
23         
24         dp = [0]* (n-1)
25         dp[0] = nums[0]
26         dp[1] = nums[0]
27         
28         for i in range(2,n-1):
29             dp[i] = max(dp[i-2]+nums[i], dp[i-1])
30         
31         case2 = dp[-1]
32         
33         return max(case1, case2)
34         
View Code

 

posted @ 2016-12-16 05:22  lettuan  阅读(187)  评论(0编辑  收藏  举报