A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) might be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
[1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) are alternately positive and negative.[1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.Given an integer array nums, return the length of the longest wiggle subsequence.
nums is empty?
nums contains only one element?
nums be?
nums unique?
To solve this problem, we can use a greedy approach:
prevDiff) between consecutive elements.def wiggleMaxLength(nums):
if len(nums) < 2:
return len(nums)
prevDiff = nums[1] - nums[0]
count = 1 if prevDiff == 0 else 2
for i in range(2, len(nums)):
diff = nums[i] - nums[i - 1]
if (diff > 0 and prevDiff <= 0) or (diff < 0 and prevDiff >= 0):
count += 1
prevDiff = diff
return count
nums. The algorithm iterates through the array once.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?