题解 | #打家劫舍(二)# python3 假设两种情况
打家劫舍(二)
https://www.nowcoder.com/practice/a5c127769dd74a63ada7bff37d9c5815
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param nums int整型一维数组 # @return int整型 # class Solution: def rob(self , nums: List[int]) -> int: n = len(nums) if n == 1: print(0) return nums[0] if n == 2 and nums[0]>nums[1]: print(1) return nums[0] elif n == 2 and nums[0]<=nums[1]: print(2) return nums[1] # write code here sum_money = 0 #偷最后一个,第一个绝对不能偷 n1=n dp1 = [0]*n1 sum_money1 = 0 dp1[1] = nums[1] dp1[2] = nums[2] for i in range(3,n): dp1[i]=max(dp1[i-1],nums[i]+dp1[i-2]) sum_money1 = dp1[n1-1] #不偷最后一个 n2 = n dp2 = [0]*n2 sum_money2 = 0 dp2[0] = nums[0] dp2[1] = nums[1] for i in range(2,n-1): dp2[i]=max(dp2[i-1],nums[i]+dp2[i-2]) sum_money2 = dp2[n2-2] print(3) return max(sum_money1,sum_money2)