Wiggle Subsequence (LeetCode 376): Solution and Explanation

Medium
Array
Dynamic Programming
Greedy

A wiggle sequence alternates strictly between rising and falling steps. Given an integer array nums, return the length of its longest subsequence that is a wiggle sequence.

Intuition

Only the sign of each step matters. Write +, - or 0 for every difference nums[i] - nums[i-1]. A zero step can never be part of a wiggle, because the differences must be strictly positive or strictly negative.

Ask what the best wiggle ending at the current point looks like, split by how its last step went. Call up the longest wiggle whose last step rises and down the longest whose last step falls. Before any step both are 1, since a single number is a wiggle.

If the new step rises, it can be appended to any wiggle that last fell, so up = down + 1. A falling step gives down = up + 1. Nothing else changes, because a wiggle that last rose cannot take another rise.

Why is it safe to always use the newest element? Within a run of rises, the latest value is the highest, and a higher peak only makes the next fall easier. So the kept turning point simply slides to the end of each run, and the answer equals the number of peaks and valleys after merging runs that go the same way.

Approach: Up/down DP in constant space

  1. Set up = down = 1.
  2. For each i from 1 to n - 1: if nums[i] > nums[i-1], set up = down + 1; if nums[i] < nums[i-1], set down = up + 1; if they are equal, do nothing.
  3. Return max(up, down).

Step-by-step example

nums = [1, 17, 5, 10, 13, 15, 10, 5, 16, 8]
  1. Start: up = 1, down = 1.
  2. 17 > 1 rises: up = 2. 5 < 17 falls: down = 3.
  3. 10 > 5 rises: up = 4. 13 and 15 keep rising, so up stays 4 while the peak slides from 10 to 15.
  4. 10 < 15 falls: down = 5. 5 < 10 falls again: down stays 5 while the valley slides to 5.
  5. 16 > 5 rises: up = 6. 8 < 16 falls: down = 7.
  6. Answer: max(6, 7) = 7, for example [1, 17, 5, 15, 5, 16, 8].

Code: Python, Java, C++

1class Solution:
2    def wiggleMaxLength(self, nums: List[int]) -> int:
3        up = down = 1
4        for i in range(1, len(nums)):
5            if nums[i] > nums[i - 1]:
6                up = down + 1
7            elif nums[i] < nums[i - 1]:
8                down = up + 1
9        return max(up, down)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the array with constant work per element.

Space

O(1)

Only the two counters up and down are kept.

Other approaches

Quadratic DP (time O(n^2), space O(n))

Keep up[i] and down[i] for every index and, for each i, scan every earlier j and extend down[j] on a rise or up[j] on a fall. Correct and easy to derive, but it does needless work.

Greedy peak and valley count (time O(n), space O(1))

Drop zero differences, then count how many times the sign of the difference changes. The answer is that count plus 2 when any nonzero difference exists, otherwise 1.

Common mistakes

  • Counting equal neighbours as a wiggle step. A zero difference must be skipped.
  • Returning 0 for a single element or an all-equal array. Any single number is a wiggle of length 1.
  • Updating up and down from each other in the same step. Only one of them changes per element, and it reads the other's current value.
  • Assuming the subsequence must be contiguous. You may skip elements, which is why a run in one direction collapses to its last point.

Frequently asked questions

Why does up = down + 1 never get worse than the old up?

down never decreases and was at least up - 1 when up was last set, so down + 1 is at least the old up. The counters only grow.

Is this dynamic programming or greedy?

Both views give the same code. As DP, up and down are the two states for the last step. As greedy, they count turning points after merging same-direction runs.

How would I recover an actual subsequence?

Keep the turning points: when the direction changes, append the current index; when it continues, replace the last kept index with the current one. The kept list is a longest wiggle.