198. 打家劫舍

2020-03-23  本文已影响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
}
上一篇下一篇

猜你喜欢

热点阅读