leetCode 198

问题

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.
使用正整数数组来表示每个房子的金钱,在不惊动警察情况下,你最多能抢到多少钱?

大概是这个意思吧。

思想

如果整条大街只有一间房子,显然:Max[1] = M[1]
如果整条大街只有两间房子,则: Max[2] = max(M[1], M[2])

假设有N个房子,第i个房子的金钱数用 M[i]来表示,而能获得最大的金钱数用Max[i]来表示。对于第i个房子,有两种选择:

  • 抢劫 i , 则说明了没有抢劫 i - 1, 所以金钱数为:Max[i - 2] + M[i]
  • 不抢劫 i , 则金钱数为:Max[i - 1]
    对着两种情况进行比较,选择大者的方案进行。

实现

func rob(_ nums: [Int]) -> Int {
    if nums.count == 0 {
        return 0
    }
    else if nums.count == 1 {
        return  nums[0]
    }
    else if nums.count == 2 {
        return max(nums[0], nums[1])
    }
    else {
        var array = [Int]()
        
        array.append(nums[0])
        array.append(max(nums[0], nums[1]))
        
        for index in 2..<nums.count {
            // 动态规划,将前面的最大值都放在数组里面保存起来
            array.append(max(nums[index] + array[index - 2], array[index - 1]))
        }
        
        return array.last!
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,196评论 0 10
  • Problem You are a professional robber planning to rob hou...
    Branch阅读 1,450评论 0 0
  • 转载引用 TCP/IP异步模型 Server 服务端基本流程创建套接字绑定套接字的IP和端口号——Bind()/C...
    语落心生阅读 4,778评论 0 0
  • 常常有人说,这个人看着好友善,这个人看着凶巴巴!可能我们并没有开口说话,但是路人已有这样的认知! 咱们中国人说话,...
    妮的夏天阅读 3,696评论 5 6
  • 今天是2017年的最后一天,也就是大年三十。 早上我还没起床,爷爷奶奶就把我给叫醒了,然后就做饭...
    小太阳教室程柯维阅读 1,310评论 0 0

友情链接更多精彩内容