美文网首页
198. 打家劫舍

198. 打家劫舍

作者: 寂灭天骄小童鞋 | 来源:发表于2020-03-23 22:36 被阅读0次

    https://leetcode-cn.com/problems/house-robber/

    func rob(_ nums: [Int]) -> Int {
        if nums.count <= 0 {return 0}
        if nums.count == 1 {return nums[0]}
        var resultArr = Array<Int>(repeating: 0, count: nums.count)
        resultArr[0] = nums[0]
        resultArr[1] = max(nums[0], nums[1])
        for idx in stride(from: 2, to: resultArr.count, by: 1) {
            resultArr[idx] = max(nums[idx] + resultArr[idx - 2], resultArr[idx - 1])
        }
        return resultArr[resultArr.count - 1]
    }
    
    func rob(_ nums: [Int]) -> Int {
        if nums.count <= 0 {return 0}
        var first = 0
        var second = 0
        for idx in stride(from: 0, to: nums.count, by: 1) {
            let tmp = second
            second = max(first + nums[idx], second)
            first = tmp
        }
        return second
    }
    

    相关文章

      网友评论

          本文标题:198. 打家劫舍

          本文链接:https://www.haomeiwen.com/subject/xjwbyhtx.html