Wiggle Subsequence

Medium

Topics
ArrayDynamic ProgrammingGreedy

A wiggle sequence has strictly alternating positive and negative differences between successive numbers. Given nums, return the length of the longest wiggle subsequence.

Example 1

174925
a longest wiggle subsequence
The shaded bars alternate up, down, up. Counting the direction changes is enough: within a monotonic run only the last element is worth keeping, so the answer is the number of turns plus one — 6 — with no table at all.
Bars are the array values, left to right.
Input:  nums = [1,7,4,9,2,5]
Output: 6

Example 2

1175101315105168
a longest wiggle subsequence
Input:  nums = [1,17,5,10,13,15,10,5,16,8]
Output: 7

Example 3

12345
a longest wiggle subsequence
Input:  nums = [1,2,3,4,5]
Output: 2

Constraints

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

A wiggle subsequence alternates rise and fall, so at every position only two facts matter: the length of the best subsequence ending here that arrived going up, and the best that arrived going down. Two integers carry the entire state.

The update is almost too simple to trust. When the array rises from the previous element, any down-ending subsequence can be extended by this element, so up = down + 1; when it falls, down = up + 1. Equal neighbours change nothing. The reason this greedy is exact is that only the direction of the last step constrains what can follow — the actual values never matter again, so there is nothing else to remember.

Approach

  1. Return the length directly for arrays shorter than two.
  2. Start up = down = 1.
  3. Walk from index 1: on a rise set up = down + 1, on a fall set down = up + 1, on a tie do nothing.
  4. Return max(up, down).

Dry Run

nums = [1,7,4,9,2,5]

  i  nums[i]  vs prev   up  down
  0  1        -         1   1
  1  7        rose      2   1
  2  4        fell      2   3
  3  9        rose      4   3
  4  2        fell      4   5
  5  5        rose      6   5

answer max(up, down) = 6

  [1,17,5,10,13,15,10,5,16,8]  -> 7
  [1,2,3,4,5]                  -> 2    one rise is all you get
  [1,1,1]                      -> 1    plateaus update neither counter
  [3]                          -> 1

Complexity

  • Time — O(n): one pass, two comparisons per element.
  • Space — O(1): two integers. The O(n²) dynamic program over all pairs is the natural first answer and is worth stating before collapsing it to this.

Common Pitfalls

  • Updating both counters on the same step. A rise tells you nothing new about the best down-ending subsequence, so down must be left alone — and writing up, down = down + 1, up + 1 on a rise corrupts it.
  • Reading the previous value from up and down after one has already been updated. In a language without simultaneous assignment the order matters; here only one of the two changes per step, so it does not — but the reason is worth knowing.
  • Counting direction changes in the raw array. That is the same answer only if you first collapse plateaus; doing it directly makes [1,1,2] come out wrong.
  • Treating equal adjacent elements as a rise or a fall. A flat step cannot be part of a wiggle, so it updates nothing.
  • Returning up or down alone. The best subsequence may end in either direction.
  • Trying to reconstruct the actual subsequence from these two counters. They are lengths only; recovering the elements needs the O(n²) table or a separate greedy pass.

Full Solution — all languages

class Solution:
    def wiggleMaxLength(self, nums):
        if len(nums) < 2:
            return len(nums)
        up = down = 1
        for i in range(1, len(nums)):
            if nums[i] > nums[i-1]:
                up = down + 1
            elif nums[i] < nums[i-1]:
                down = up + 1
        return max(up, down)
SensAI
Beta
Tap the mic to stop voice mode