sagelearnai

Wiggle Subsequence

Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #376

A wiggle sequence's consecutive differences strictly alternate in sign (zero differences don't count). A one-element sequence, and a two-element sequence of distinct values, are trivially wiggles. Return the length of the longest wiggle subsequence of nums.

Examples

text
[1,7,4,9,2,5]                →  6
[1,17,5,10,13,15,10,5,16,8]  →  7
[1,2,3,4,5,6,7,8,9]          →  2

Hints

  1. Track two lengths: the longest wiggle ending with an up-move, and the longest ending with a down-move.

Approach

up = the longest wiggle subsequence so far whose last difference is positive, and down similarly for negative. For each i:

  • nums[i] > nums[i−1] → up = down + 1
  • nums[i] < nums[i−1] → down = up + 1
  • equal → no change

The answer is max(up, down), starting from up = down = 1.

Greedy view: count the turning points (local peaks and valleys) after removing the flat steps.

Complexity

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

Python solution
def wiggleMaxLength(nums):
    up = down = 1
    for a, b in zip(nums, nums[1:]):
        if b > a:
            up = down + 1
        elif b < a:
            down = up + 1
    return max(up, down)
JavaScript solution
function wiggleMaxLength(nums) {
  let up = 1, down = 1;
  for (let i = 1; i < nums.length; i++) {
    if (nums[i] > nums[i - 1]) up = down + 1;
    else if (nums[i] < nums[i - 1]) down = up + 1;
  }
  return Math.max(up, down);
}