Lintcode打劫房屋

Lintcode 打劫房屋

典型的动态规划,方程:
f(n) = max{L(n) + f(n-2), f(n-1)}

python代码

class Solution:
    # @param A: a list of non-negative integers.
    # return: an integer
    def houseRobber(self, A):
        # write your code here
        L = A
        len_L = len(L)
        if len_L == 0:
            return 0
        if len_L == 1:
            return L[0]
        ans_list = [0 for i in range(len_L)]
        ans_list[0] = L[0]
        ans_list[1] = L[1]
        for i in range(2, len_L):
            ans_list[i] = max(ans_list[i-2] + L[i], ans_list[i-1])
        return max(ans_list)

你可能感兴趣的:(python)