题目描述
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
解题思路
动态规划求解不连续子序列的最大和。使用数组 DP 存储已有的历史记忆,DP[i] 表示偷窃以 i 结尾的最大值。
代码
class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
dp = [0] * n
dp[0] = nums[0]
for i in range(1, n):
if i == 1:
dp[i] = max(nums[0], nums[1])
else:
dp[i] = max(dp[:i - 1]) + nums[i]
return max(dp)