9 lines of swift code. O(n) time complexity.


  • 0
    J
    func rob(_ nums: [Int]) -> Int {
            if nums.count < 2 {
                return nums.count > 0 ? nums[0] : 0
            }
            var has = nums[0], not = 0, has1 = 0, not1 = 0
            for i in 1..<nums.count {
                (has, not) = (not+nums[i], max(has, not))
                (has1,not1)=(not1+nums[i], max(has1,not1))
            }
            return max(has1, not)
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.