algoadvance

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.

Given an integer array nums, return the length of the longest wiggle subsequence.

Clarifying Questions

  1. What if the input nums is empty?
    • Return 0.
  2. What if the input nums contains only one element?
    • Return 1 since a single element is trivially a wiggle sequence.
  3. How large can the input array nums be?
    • The input array can have up to (10^4) elements.
  4. Are all values in nums unique?
    • No guarantee that all values are unique.

Strategy

To solve this problem, we can use a greedy approach:

  1. Iterate through the array while keeping track of the previous difference (prevDiff) between consecutive elements.
  2. Update the count of the wiggle sequence every time we find a valid “wiggle” (i.e., a change in the direction of the difference).
  3. The count starts at 1 due to the first element of the array being part of the sequence by default.

Code

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

Time Complexity

Try our interview co-pilot at AlgoAdvance.com