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.

Example Given [3, 8, 4], return 8.

思路: dp[i]代表 nums[0:i]最多能抢多少钱, dp[i] = max(dp[i-1], dp[i-2]+ nums[i])。就是一个根据前面2个状态决定当前这个房子抢还是不抢。

LC: https://leetcode.com/problems/house-robber/

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0

        # if house smaller than 2.
        if len(nums)<=2:
            return max(nums)

        # init first 2 
        dp = [0]+[nums[0]]

        # do the dp loop
        for i in range(1, len(nums)):
            dp.append(max(dp[-2]+nums[i], dp[-1]))

        return dp[-1]

so = Solution()
print so.rob([2,3,5,2,1])

Follow up: The dp array can be replaced by 2 variables. second_last, and last

results matching ""

    No results matching ""