Imagine you're tracking a roller coaster's ups and downs - that's exactly what a wiggle sequence is! A wiggle sequence alternates between going up and down, where the differences between consecutive numbers strictly alternate between positive and negative.
๐ข What makes a sequence "wiggle"?
- The differences between successive numbers must strictly alternate between positive and negative
- The first difference can be either positive or negative
- Single elements and two non-equal elements are trivially wiggle sequences
Examples:
[1, 7, 4, 9, 2, 5] โ
Wiggle! Differences: (6, -3, 5, -7, 3) - alternates perfectly
[1, 4, 7, 2, 5] โ Not wiggle! First two differences (3, 3) are both positive
[1, 7, 4, 5, 5] โ Not wiggle! Last difference is zero
Your Mission: Given an integer array nums, find the length of the longest wiggle subsequence. Remember, a subsequence maintains the original order but can skip elements.
Input & Output
Visualization
Time & Space Complexity
Single pass through the array, constant work per element
Only two variables needed to track the DP states
Constraints
- 1 โค nums.length โค 1000
- 0 โค nums[i] โค 1000
- Follow up: Could you solve this in O(n) time?