Swift Implementation Time O(n), Space O(1)


  • 0
    I
    class Solution {
        func rob(_ nums: [Int]) -> Int {
            if (nums.count == 1)
            {
                return nums[0]
            }
            var now = 0
            var last = 0
            for i in 0..<nums.count
            {
                var temp = last
                last = now
                now = max(now,nums[i] + temp)
            }
            return now
        }
    }
    
    

Log in to reply
 

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