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:
1 | Input: [2,3,2] |
Example 2:
1 | Input: [1,2,3,1] |
Solution
和House Robber I的不同点就是房子是围城一个圈的,即若偷第一个房子,则最后一个房子不能偷了
第一个房子偷与不偷的两种情况如下:
- 偷第一个房子,则最后一个不能偷了,即
nums[2:-1]
按照House Robber I求解, 结果再加上nums[0] - 不偷第一个房子,后面
nums[1:]按
照House Robber I求解
上面两种情况的最大值即为解。
Python:
1 | class : |