Leetcode-House Robber

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.

你是一名专业的强盗,计划抢劫沿街的房屋。 每间房屋都藏有一定数量的金钱,唯一阻止你抢劫每间房屋的限制因素是邻近的房屋有保安系统连接,如果在同一晚上有两间相邻的房屋被闯入,它将自动与警方联系。

给出一份代表每个房屋的金额的非负整数列表,确定你可以在没有提醒警方的情况下抢劫的最高金额。

 1 class Solution:
 2     def rob(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         last, now = 0, 0
 8         for i in nums:
 9             last, now = now, max(last + i, now)   
10         return now

规律:

f(0) = nums[0]
f(1) = max(num[0], num[1])
f(k) = max( f(k-2) + nums[k], f(k-1) )

 

posted on 2018-04-20 20:43  Guo磊  阅读(89)  评论(0编辑  收藏  举报

导航