Greedy Algorithms8 sections · 316 units
Open in Course

Wiggle Subsequence - Implementation

The code

Here is the solution:

function wiggleMaxLength(nums)
 if length <= 1 then
 return length
 up := 1
 down := 1
 for i from 1 to length - 1
 if nums[i] > nums[i-1] then
 up := down + 1
 else if nums[i] < nums[i-1] then
 down := up + 1
 return max(up, down)

Time: O(n)O(n). Space: O(1)O(1).

upup = length of longest wiggle ending with an up move. downdown = ending with down move. Each move extends the opposite direction.