dp[i]表示打劫到当前第 i 家的最大金额
首先,前3家特殊处理
然后,是否打劫当前家应考虑打劫 i-2 家和 i-3 是否能达到最大收益,因为不能打劫邻居 i-1
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
dp = [0] * n # 初始钱包为0
dp[0] = nums[0]
if n == 1:
return nums[0]
if n == 2:
dp[1] = max(nums[0], nums[1])
return dp[1]
if n >= 3:
dp[1] = max(nums[0], nums[1])
dp[2] = max(nums[0] + nums[2], nums[1])
for i in range(3, n):
dp[i] = max(dp[i - 2] + nums[i], dp[i - 3] + nums[i])
res = -1
for i in range(n):
res = max(dp[i], res)
return res
if __name__ == '__main__':
nums = [1, 2, 1, 1]
Sol = Solution()
res = Solution.rob(Sol, nums)
print(res)
|