Sponsored
Sponsored
In this approach, we maintain a greedy solution by keeping track of directions of the growing and shrinking sequences. We scan through the array, checking the differences between consecutive numbers. Whenever a change in the sign is detected, it contributes to a count of the longest wiggle sequence.
This approach efficiently computes in O(n) time by scanning the list only once.
Time Complexity: O(n).
Space Complexity: O(1).
1function wiggleMaxLength(nums) {
2 if (nums.length < 2) return nums.length;
3 let up = 1, down = 1;
4 for (let i = 1; i < nums.length; i++) {
5 if (nums[i] > nums[i - 1])
6 up = down + 1;
7 else if (nums[i] < nums[i - 1])
8 down = up + 1;
9 }
10 return Math.max(up, down);
11}
12
13let nums = [1, 7, 4, 9, 2, 5];
14console.log(wiggleMaxLength(nums));
JavaScript implementation utilizes two counters, up
and down
, to keep track of potential wiggle sequences as we iterate through the input array. The counters are updated based on observed trends between consecutive elements.
This solution involves using dynamic programming to keep track of two arrays - up[i]
and down[i]
where up[i]
and down[i]
indicate the longest wiggle subsequence ending at index i
with an upward or downward difference respectively.
This allows evaluating the longest wiggle subsequence leading to a time complexity of O(n^2), given we evaluate each index pair combination.
Time Complexity: O(n^2).
Space Complexity: O(n).
1
This Java solution also utilizes two arrays to represent different wiggle subsequences. The array tracking is similar, ensuring that every comparison between elements updates these subsequence lengths correctly.