The "Wiggle Subsequence" problem asks for the length of the longest subsequence that follows the wiggle pattern (differences between successive numbers alternate between positive and negative). Unlike the wiggle sort, this is about finding the longest subsequence (elements don't have to be contiguous), not reordering the whole array.
This is a classic Dynamic Programming and Greedy problem. Companies like Bloomberg ask this to see if a candidate can optimize a DP solution from O(N^2) down to O(N). It requires recognizing that we only care about the "peaks" and "valleys" of the array's trend.
The optimal approach is Greedy. We only care about how many times the direction of the sequence changes (from increasing to decreasing or vice-versa). We can maintain two variables: up (the length of the longest wiggle sequence ending with an increasing step) and down (the length of the longest wiggle sequence ending with a decreasing step).
Array: [1, 7, 4, 9, 2, 5].
1 -> 7: Increasing. up = down + 1 = 2.7 -> 4: Decreasing. down = up + 1 = 3.4 -> 9: Increasing. up = down + 1 = 4.9 -> 2: Decreasing. down = up + 1 = 5.2 -> 5: Increasing. up = down + 1 = 6.
Longest wiggle subsequence length is 6.
If the array was [1, 2, 3], the length would only be 2 because there is no direction change.dp[i][j] when only two state variables are needed.When dealing with subsequences and trends, visualize the array as a line graph. The wiggle subsequence length is essentially the number of times the graph changes direction plus one. This "peak-valley" logic is a very efficient greedy pattern.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Best Time to Buy and Sell Stock with Transaction Fee | Medium | Solve | |
| Jump Game II | Medium | Solve | |
| Jump Game | Medium | Solve | |
| Best Time to Buy and Sell Stock II | Medium | Solve | |
| Check if it is Possible to Split Array | Medium | Solve |