House Robber - LeetCode

House Robber - LeetCode

题目:

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.


分析:

这道题目用的也是动态规划,我们从题目中知道不能偷两家相邻的,所以假设我们偷到i家时,最大钱数Max(i) = max(Max(i-1),Max(i-2)+m(i-1)) 也就是比较第i-1家与偷第i-2家加上第i家的大小。


代码:

class Solution:
    # @param num, a list of integer
    # @return an integer
    def rob(self, num):
        size = len(num)
        odd, even = 0, 0
        for i in range(size):
            if i % 2:
                odd = max(odd + num[i], even)
            else:
                even = max(even + num[i], odd)
        return max(odd, even)


你可能感兴趣的:(LeetCode,python,动态规划)