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[i]表示打劫到第i间房间时候的最大值(包含或者不包含i),其实可以更清晰地用global和local来表示是否包含第i间房子。

dp[i] = max(dp[i - 1], dp[i - 2] + num[i - 1])

还可以简化将空间复杂度变为O(1)

Solution

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        length = len(nums)
        globalDP = [0 for i in range(length)]
        localDP = [0 for i in range(length)]

        globalDP[0] = nums[0]
        localDP[0] = nums[0]
        for i in range(1, length):
            if i == 1:
                localDP[i] = nums[1]
                globalDP[i] = max(nums[0], nums[1])
            else:
                localDP[i] = globalDP[i-2] + nums[i]
                globalDP[i] = max(localDP[i], localDP[i-1])

        return globalDP[-1]

Reference