题解 | #打家劫舍(二)#
打家劫舍(二)
https://www.nowcoder.com/practice/a5c127769dd74a63ada7bff37d9c5815
class Solution: def rob(self , nums: List[int]) -> int: l = len(nums) dp1 = [0 for _ in range(l+1)] dp2 = [0 for _ in range(l+1)] dp1[1] = nums[0] for i in range(2, l+1): dp1[i] = max(dp1[i-1], dp1[i-2]+nums[i-1]) dp2[i] = max(dp2[i-1], dp2[i-2]+nums[i-1]) # dp1代表偷第一家,不偷最后一家,所以最后一位不参与比较 return max(dp1[-2], dp2[-1])