【Leetcode】 House Robber

2018-03-02  本文已影响0人  flowerAO

题目

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.

思路

由于是非负整数,最后得到的值一定包含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]
上一篇 下一篇

猜你喜欢

热点阅读