Lintcode 392. House Robber (Medium) (Python)

House Robber

Description:

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.

Challenge
O(n) time and O(1) memory.

Code:

class Solution:
    """
    @param A: An array of non-negative integers
    @return: The maximum amount of money you can rob tonight
    """
    def houseRobber(self, A):
        # write your code here
        if not A:
            return 0
        lA = len(A)
        if lA==1:
            return A[0]
        dp = [0 for i in range(lA)]
        dp[0] = A[0]
        dp[1] = max(A[0], A[1])
        for i in range(2, lA):
            dp[i] = max(dp[i-2]+A[i], dp[i-1])
        return dp[lA-1]

猜你喜欢

转载自blog.csdn.net/weixin_41677877/article/details/82556408
今日推荐