Leetcode 198 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.

离散的问题求最大值,首先应该想到用DP。例如 nums = [2, 3, 1, 5, 7, 8]

dp[0] = 2, dp[1] = max(nums[0], nums[1]) 这两个点需要单独操作。 dp[i]的值取决于[i]这一家是不是要偷。如果不偷的话,dp[i] = dp[i-1]。如果偷的话,[i-1]这一家就不能偷,所以 dp[i] = dp[i-2] + nums[i]。所以dp[i] = max(dp[i-1], dp[i-2]+nums[i])。

     def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
n = len(nums)
if n == 1:
return nums[0]
if n == 2:
return max(nums[0], nums[1]) dp = [0]*n
dp[0] = nums[0]
dp[1] = max(nums[1], nums[0]) for i in range(2, n):
dp[i] = max(dp[i-2]+nums[i], dp[i-1]) return dp[-1]

本质上并不需要保存dp list中的所有值,只需要保存两个,分别对应even and odd position。 这样的话可以写成:

     def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a, b = 0, 0
n = len(nums) for i in range(n):
if i % 2 == 0:
a += nums[i]
a = max(b, a)
else:
b += nums[i]
b = max(a, b) return max(a, b)
上一篇:html2canvaces用法,js截屏并且下载


下一篇:PHP 7 安装 Memcache 和 Memcached 总结