Leetcode – House Robber 解析
题目链接:
https://leetcode.com/problems/house-robber/
答案
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
if length == 0:
return 0
if length == 1:
return nums[0]
### Optimal solution when at 0
prev = nums[0]
### Optimial solution when at 1
curr = max(nums[1], nums[0])
### Let prev be the optimal solution at i-1
### Let curr be the optimal solution at i
### For i+1, the optimal solution be the bigger one of nums[i] + prev, curr
for i in range(2, length):
tmp = max(prev+nums[i], curr)
prev = curr
curr = tmp
return max(prev, curr)