当前位置:网站首页>力扣-198.打家劫舍
力扣-198.打家劫舍
2022-04-23 16:03:00 【Node_Su】

dp[i]表示打劫到当前第 i 家的最大金额
首先,前3家特殊处理
然后,是否打劫当前家应考虑打劫 i-2 家和 i-3 是否能达到最大收益,因为不能打劫邻居 i-1
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
dp = [0] * n # 初始钱包为0
dp[0] = nums[0]
if n == 1:
return nums[0]
if n == 2:
dp[1] = max(nums[0], nums[1])
return dp[1]
if n >= 3:
dp[1] = max(nums[0], nums[1])
dp[2] = max(nums[0] + nums[2], nums[1])
for i in range(3, n):
dp[i] = max(dp[i - 2] + nums[i], dp[i - 3] + nums[i])
res = -1
for i in range(n):
res = max(dp[i], res)
return res
if __name__ == '__main__':
nums = [1, 2, 1, 1]
Sol = Solution()
res = Solution.rob(Sol, nums)
print(res)
版权声明
本文为[Node_Su]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Node_Su/article/details/124363035
边栏推荐
猜你喜欢

Filter usage of spark operator

JVM - Chapter 2 - class loader subsystem

Homewbrew installation, common commands and installation path

matplotlib教程05---操作图像

R语言中实现作图对象排列的函数总结

R语言中绘制ROC曲线方法二:pROC包

Partitionby of spark operator

The principle and common methods of multithreading and the difference between thread and runnable

实现缺省页面

Nanny Anaconda installation tutorial
随机推荐
Upgrade MySQL 5.1 to 5.610
Implement default page
新动态:SmartMesh和MeshBox的合作新动向
捡起MATLAB的第(3)天
Algorithem_ ReverseLinkedList
【自娱自乐】构造笔记 week 2
Day (7) of picking up matlab
One brush 313 sword finger offer 06 Print linked list from end to end (E)
How do you think the fund is REITs? Is it safe to buy the fund through the bank
多线程原理和常用方法以及Thread和Runnable的区别
Accumulation of applet knowledge points
Go concurrency and channel
Interview questions of a blue team of Beijing Information Protection Network
Spark 算子之filter使用
How can poor areas without networks have money to build networks?
Distinct use of spark operator
Unity Shader学习
js正則判斷域名或者IP的端口路徑是否正確
Review 2021: how to help customers clear the obstacles in the last mile of going to the cloud?
PS为图片添加纹理