Swift solution - Dynamic Programming


  • 0
    class Solution {
        func wiggleMaxLength(_ nums: [Int]) -> Int {
            if nums.count < 2 {
                return nums.count
            }
            
            let count = nums.count
            var up = [Int](repeatElement(0, count: count))
            var down = [Int](repeatElement(0, count: count))
            
            up[0] = 1
            down[0] = 1
            for i in 1..<count {
                if nums[i] > nums[i - 1] {
                    up[i] = down[i - 1] + 1
                    down[i] = down[i - 1]
                } else if nums[i] < nums[i - 1] {
                    down[i] = up[i - 1] + 1
                    up[i] = up[i - 1]
                } else {
                    down[i] = down[i - 1]
                    up[i] = up[i - 1]
                }
            }
            
            return max(down[count - 1], up[count - 1])
        }
    }
    

Log in to reply
 

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