Leetcode 376. Wiggle Subsequence
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (7-1=6), (4-7=-3), (9-4=5), (2-9=-7), and (5-2=3) are alternately positive and negative. Another example is [1, 4, 7, 2, 5] which is not a wiggle sequence because [4-1=3] and [7-4=3] are not alternating.
Given an integer array nums, return the length of the longest wiggle sequence.
nums = [1,7,4,9,2,5]
Output: 6nums = [1,17,5,10,13,15,10,5,16,8]
Output: 7nums = [1,2,3,4,5,6,7,8,9]
Output: 21 <= nums.length <= 10000 <= nums[i] <= 1000Q: Are there any constraints on the elements of the array (e.g., non-negative)? A: Yes, the elements range from 0 to 1000.
Q: Should the sequence be strictly alternating or can it have consecutive equal elements? A: The sequence should have strictly alternating differences between consecutive elements.
Q: How should single-element arrays be treated? A: A single-element array is trivially a wiggle sequence, so the length should be 1.
To tackle this problem efficiently, we will use a greedy approach. The idea is to iterate over the array and maintain two variables: up and down.
up keeps track of the length of the longest wiggle sequence ending with an upward wiggle.down keeps track of the length of the longest wiggle sequence ending with a downward wiggle.While iterating through the array:
up.down.By the end of the traversal, the maximum of up and down will give us the length of the longest wiggle sequence.
public class Solution {
public int wiggleMaxLength(int[] nums) {
if (nums.length < 2) {
return nums.length;
}
// Initialize up and down
int up = 1;
int down = 1;
// Traverse the array from the second element
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
up = down + 1;
} else if (nums[i] < nums[i - 1]) {
down = up + 1;
}
}
// The result is the maximum between up and down
return Math.max(up, down);
}
}
The time complexity of the above code is O(n), where n is the number of elements in the input array nums. This is because we are iterating through the array once.
Feel free to ask any further questions or for additional explanations!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?