A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative. In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array nums, return the length of the longest wiggle subsequence of nums.
Function Signature
def wiggle_max_length(nums: list[int]) -> int:
Rules
-
A difference of zero is never allowed inside a wiggle sequence, so two equal values can never be adjacent in the chosen subsequence.
-
Return only the length. Several subsequences may reach the maximum length, and any of them gives the same answer.
Constraints
-
1 <= len(nums) <= 1000
-
0 <= nums[i] <= 1000
Examples
Input: nums = [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3), so nothing needs to be deleted.
Input: nums = [1,17,5,10,13,15,10,5,16,8]
Output: 7
One longest wiggle subsequence is [1, 17, 10, 13, 10, 16, 8], with differences (16, -7, 3, -3, 6, -8). The array has only six stretches that move in one direction (up, down, up, down, up, down), so no wiggle subsequence can have more than seven elements.
Input: nums = [4,4,7,7,7,2,2]
Output: 3
Repeated values add nothing, so the useful values are 4, 7, 2. That subsequence goes up and then down, which gives length 3.