Leetcode: House Robber

来源:互联网 发布:openal是什么软件 编辑:程序博客网 时间:2024/06/14 18:22

Question

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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

Hide Tags Dynamic Programming


Analysis


Solution

v1. Space Complexity: O(n)

class Solution:    # @param {integer[]} nums    # @return {integer}    def rob(self, nums):        if len(nums)==0:            return 0        if len(nums)<=2:            return max(nums)        res = [0]*len(nums)        res[0],res[1] = nums[0],max(nums[0:2])        for i in range(2,len(res)):            res[i] = max(res[i-1],res[i-2]+nums[i])        return res[-1]    


v2. Space Complexity O(1)

class Solution:    # @param {integer[]} nums    # @return {integer}    def rob(self, nums):        if len(nums)==0:            return 0        if len(nums)<=2:            return max(nums)        l1,l2 = nums[0],max(nums[0:2])        res = 0        for i in range(2,len(nums)):            temp = l2            l2 = max(l2, l1+nums[i])            l1 = temp        return l2


0 0