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).
1public class Solution {
2 public int wiggleMaxLength(int[] nums) {
3 if (nums.length < 2) return nums.length;
4 int up = 1, down = 1;
5 for (int i = 1; i < nums.length; i++) {
6 if (nums[i] > nums[i - 1])
7 up = down + 1;
8 else if (nums[i] < nums[i - 1])
9 down = up + 1;
10 }
11 return Math.max(up, down);
12 }
13 public static void main(String[] args) {
14 Solution sol = new Solution();
15 int[] nums = {1, 7, 4, 9, 2, 5};
16 System.out.println(sol.wiggleMaxLength(nums));
17 }
18}
The Java solution implements the greedy approach similar to the previous examples. Here we also use two variables up
and down
indicating the longest wiggle sequence from increasing and decreasing sides.
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 approach makes use of two additional arrays up
and down
which are dynamically allocated to store the longest wiggle subsequence lengths. For each element, it checks all previous elements to update up
and down
arrays.