【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.

思路

  • 给一个非负整数List,求相加最大值
  • 限制条件:不能同时加相邻的数字

由于是非负整数,最后得到的值一定包含l[-1]或者l[-2]。可以直接利用原数组. 首先对长度为0、1、2进行处理。对长度大于2的List,i==1,值为i==0和i==1其中最大值。从i == 2起,对于每个i, dp[i] = max(dp[i-2] + dp[i], dp[i-1]) ,

故如下AC code:

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

你可能感兴趣的:(【Leetcode】 House Robber)