198. House Robber

问题描述

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.

思路

类似DP的思路
i天能拿到的钱,等于max(dp[i-1], dp[i-2]+nums[i]),因为不能连着两户都拿
注意dp[i-1]并不一定包含[i-1]这天的钱,只是到这天为止可拿到的最大值dp[i-2]同理
因为此题只要返回最大值,可以只保留cur = dp[i-1]pre = dp[i-2]

    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = len(nums)
        if length == 0:
            return 0
        if length == 1:
            return nums[0]
        pre, cur = nums[0], max(nums[0],nums[1])
        for i in range(2, length):
            pre, cur = cur, max(cur, pre+nums[i])
        return max(pre, cur)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,167评论 0 10
  • You are a professional robber planning to rob houses alon...
    灰睛眼蓝阅读 1,612评论 0 0
  • 今天从书上看到一段话:“你所有的怒气与歇斯底里,其实只是对自己无法改变现状,无力的一种表现而已。”我就想到自从...
    Jenny吉祥三宝阅读 1,648评论 0 0
  • 今天继续前行。开始第三课,统计。 其实统计真的好简单,有没有 继续做数列,每次换一点,比比都不会…没事,不会就一起...
    优雅黑鸟阅读 1,355评论 0 0
  • 生有一对犄角 花开别样红 从不屑于隐藏丑陋 于是花随她而开 有一夜风起 花落漫天飘零 她看见万家灯火 开始摸索 身...
    夜白H阅读 1,090评论 0 2

友情链接更多精彩内容