[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
本文介绍LeetCode上198题House Robber的解题思路及实现过程。该题目标是在不连续抢劫相邻房屋的情况下获得最大金额。采用动态规划的方法,通过迭代更新两个变量来跟踪当前和前一房屋的最大收益。
443

被折叠的 条评论
为什么被折叠?



