代码
python
# encoding = utf-8
# 开发者:Alen
# 开发时间: 14:03
# "Stay hungry,stay foolish."
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
rob1, rob2 = 0, 0
# [rob1, rob2, n, n+1]
for num in nums:
temp = max(num + rob1, rob2)
rob1, rob2 = rob2, temp
return rob2
迭代过程
python
# nums = [2, 7, 9, 3, 1]
num = 2:
temp = max(0 + 2, 0) = 2
rob1 = 0, rob2 = 2
num = 7:
temp = max(0 + 7, 2) = 7
rob1 = 2, rob2 = 7
num = 9:
temp = max(2 + 9, 7) = 11
rob1 = 7, rob2 = 11
num = 3:
temp = max(7 + 3, 11) = 11
rob1 = 11, rob2 = 11
num = 1:
temp = max(11 + 1, 11) = 12
rob1 = 11, rob2 = 12
最终结果
返回 rob2 = 12
最优方案是:抢劫第1个(2)、第3个(9)、第5个(1)个房屋 = 2 + 9 + 1 = 12
为什么这样是有效的?
这个算法的高明之处在于:
-
滚动数组思想:只保存前两个状态,空间复杂度O(1)
-
最优子结构:每个位置的最优解只依赖于前两个位置的最优解
-
决策完备性:在每个位置,我们都考虑了所有可能的决策(抢或不抢)
时间复杂度
-
时间复杂度:O(n),只需要一次遍历
-
空间复杂度:O(1),只用了两个变量
结果
解题步骤:https://www.bilibili.com/video/BV1UprvBUEuH/?vd_source=15b4bc8968fa5203cc470cb68ff72c96
