Swift DP Solution, Time O(n), Space O(1)


  • 0
    I
    class Solution {
        func rob(_ nums: [Int]) -> Int {
            if(nums.count == 0)
            {
                return 0
            }
            if (nums.count == 1)
            {
                return nums[0]
            }
            
            return max(maxValue(0,nums.count-1,nums),maxValue(1,nums.count,nums))
        }
        func maxValue(_ start:Int,_ end:Int,_ nums:[Int]) ->Int
        {
            var last = 0
            var now = 0
            for i in start..<end
            {
                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.