难度指数:⭐⭐⭐⭐⭐
知识点:动态规划
算法参考:
class Solution:
def rob(self, nums: [int]) -> int:
def my_rob(nums):
cur, pre = 0, 0
for num in nums:
cur, pre = max(pre + num, cur), cur
return cur
return max(my_rob(nums[:-1]),my_rob(nums[1:])) if len(nums) != 1 else nums[0]
作者:Krahets
链接:https://leetcode.cn/problems/house-robber-ii/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
def rob(nums):
def robRange(start, end):
first = nums[start]
second = max(nums[start], nums[start + 1])
for i in range(start + 2, end + 1):
first, second = second, max(first + nums[i], second)
return second
length = len(nums)
if length == 1:
return nums[0]
elif length == 2:
return max(nums[0], nums[1])
else:
return max(robRange(0, length - 2), robRange(1, length - 1))
nums = [int(x) for x in input().split(" ")]
print(rob(nums))
Mine:
idea
- 将环断开,消除第N个格子对第一个格子的制约。
- 分两种情况:第N个格子或第一个格子不用
代码实现
def max_score(grids):
def dp(nums):
pre=nums[0]
cur=max(num[0],nums[1])
for i in range(2,len(nums)):
cur,pre=max(cur,pre+nums[i]),cur
return cur
return max(dp(grids[0:N-1]),dp(grids[1:N])) if len(grids)!=1 else grids[0]