lintcode练习 - 392. 打劫房屋

版权声明:原创部分都是自己总结的,如果转载请指明出处。觉得有帮助的老铁,请双击666! https://blog.csdn.net/qq_36387683/article/details/81910323

392. 打劫房屋

假设你是一个专业的窃贼,准备沿着一条街打劫房屋。每个房子都存放着特定金额的钱。你面临的唯一约束条件是:相邻的房子装着相互联系的防盗系统,且 当相邻的两个房子同一天被打劫时,该系统会自动报警

给定一个非负整数列表,表示每个房子中存放的钱, 算一算,如果今晚去打劫,你最多可以得到多少钱 在不触动报警装置的情况下

样例

给定 [3, 8, 4], 返回 8.

挑战

O(n) 时间复杂度 且 O(1) 存储。

解题思路:

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 len(A) == 0:
            return 0
        dp = [0] * (len(A)+1)
        dp[1] = A[0]
        for i in range(1, len(A)):
            dp[i+1] = max(A[i] + dp[i-1], dp[i])
            
        return dp[-1]
    '''
    def houseRobber(self, A):
        prevmax,currmax=0,0
        for i in range(len(A)):
            currmax,prevmax=max(prevmax+A[i],currmax),currmax
            # print(currmax, prevmax)
        return currmax

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81910323