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).
1using System;
2
3public class Solution {
4 public int WiggleMaxLength(int[] nums) {
5 if (nums.Length < 2) return nums.Length;
6 int up = 1, down = 1;
7 for (int i = 1; i < nums.Length; i++) {
8 if (nums[i] > nums[i - 1])
9 up = down + 1;
10 else if (nums[i] < nums[i - 1])
11 down = up + 1;
12 }
13 return Math.Max(up, down);
14 }
15 public static void Main() {
16 Solution sol = new Solution();
17 int[] nums = {1, 7, 4, 9, 2, 5};
18 Console.WriteLine(sol.WiggleMaxLength(nums));
19 }
20}
The C# solution mirrors the other greedy strategy implementations. It utilizes indices to iterate through the input array to look for alternating increasing and decreasing sequences, adjusting the up
and down
lengths accordingly.
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.