Problem Description
Given an integer array nums, a wiggle sequence is one where the successive differences between numbers strictly alternate between positive and negative. A subsequence is obtained by deleting some elements without changing the order. The task is to find the length of the longest wiggle subsequence.
Key Insights
- A single element or two distinct elements are trivial wiggle subsequences.
- The sign of the difference between successive elements is what matters; only count changes when the sign flips (ignoring zeros).
- A greedy approach can be applied by iterating once through the array and tracking the current direction (positive or negative).
- Dynamic programming is also possible but not necessary since O(n) time can be achieved with the greedy approach.
Space and Time Complexity
Time Complexity: O(n) – we traverse the array once.
Space Complexity: O(1) – only a few extra variables are used.
Solution
We start by checking if the list has fewer than two elements; if so, that length is the answer. Then, we initialize a counter (result) and a variable to store the last non-zero difference between consecutive elements. For each element in the array, calculate the current difference. If the current difference and the previous difference have opposite signs (one positive and one negative), then it indicates a valid wiggle and we increase our counter and update the previous difference. This ensures every valid "turn" is counted in the subsequence.