Wiggle Subsequence - Problem

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.

Input & Output

Example 1 — Standard Wiggle Sequence
$ Input: nums = [1,7,4,9,2,5]
Output: 6
💡 Note: The entire array forms a wiggle sequence with differences [+6,-3,+5,-7,+3] alternating between positive and negative. All 6 elements can be included.
Example 2 — Non-Wiggle Array
$ Input: nums = [1,4,7,2,5]
Output: 4
💡 Note: The differences are [+3,+3,-5,+3]. The first two differences are both positive, so we can pick subsequence [1,7,2,5] with differences [+6,-5,+3] for length 4.
Example 3 — Equal Elements
$ Input: nums = [1,7,4,5,5]
Output: 4
💡 Note: The last difference is zero (5-5=0), so we exclude one of the final 5s. Optimal subsequence is [1,7,4,5] with length 4.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Wiggle Subsequence: Find Longest Alternating PatternInput: [1, 7, 4, 9, 2, 5]174925+6-3+5-7+3Differences alternate: ↗ ↘ ↗ ↘ ↗✓ Perfect Wiggle Sequence!Length = 6 (all elements included)
Understanding the Visualization
1
Input Array
Given array [1,7,4,9,2,5] with elements
2
Find Differences
Calculate differences: +6, -3, +5, -7, +3
3
Check Alternation
Differences alternate signs: positive, negative, positive, negative, positive
Key Takeaway
🎯 Key Insight: A wiggle subsequence is longest when we include all local peaks and valleys where the trend changes
Asked in
Google 15 Microsoft 12 Amazon 8 Facebook 6
185.0K Views
Medium Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen