当前位置:网站首页>力扣-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
边栏推荐
猜你喜欢
Distinct use of spark operator
Unity Shader学习
Spark 算子之distinct使用
保姆级Anaconda安装教程
Ice -- source code analysis
Intersection, union and difference sets of spark operators
撿起MATLAB的第(9)天
Do we media make money now? After reading this article, you will understand
Filter usage of spark operator
Best practices of Apache APIs IX high availability configuration center based on tidb
随机推荐
The system research problem that has plagued for many years has automatic collection tools, which are open source and free
Leetcode-396 rotation function
Coalesce and repartition of spark operators
PS add texture to picture
Vision of building interstellar computing network
Fastjon2他来了,性能显著提升,还能再战十年
JS regular détermine si le nom de domaine ou le chemin de port IP est correct
C, calculation method and source program of bell number
捡起MATLAB的第(10)天
Homewbrew installation, common commands and installation path
一文掌握vscode远程gdb调试
Calculate the number of occurrences of a character
多线程原理和常用方法以及Thread和Runnable的区别
【开源工具分享】单片机调试助手(示波/改值/日志) - LinkScope
贫困的无网地区怎么有钱建设网络?
ES常用查询、排序、聚合语句
utils. Deprecated in35 may be cancelled due to upgrade. What should I do
Install redis and deploy redis high availability cluster
[split of recursive number] n points K, split of limited range
Config组件学习笔记