[leetcode]198.House Robber
题目链接
https://leetcode.com/problems/house-robber/description/
题目描述
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 system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
题目大意
给定一个非负数的序列,求其满足元素不相邻的最大子序列。
解题思路
递推式
f(0) = nums[0]
f(1) = max( nums[0], nums[1])
f(k) = max( f(k-2) + nums[k], f(k-1) )
代码
class Solution:
def rob(self, nums):
last, now = 0, 0
for i in nums:
last, now = now, max(last + i, now)
return now