LeetCode 376. Wiggle Subsequence

Post by ailswan Mar. 01, 2024

376. Wiggle Subsequence

Problem Statement

link: LeetCode.cn LeetCode

A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.

For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative. In contrast, [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. A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.

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

Example:

Input: nums = [1,7,4,9,2,5] Output: 6

Input: nums = [1,17,5,10,13,15,10,5,16,8] Output: 7

Input: nums = [1,2,3,4,5,6,7,8,9] Output: 2

Solution Approach

This solution utilizes a greedy approach to efficiently find the length of the longest wiggle subsequence.

Algorithm

  1. Initialize variables to track the difference between consecutive elements (pre) and the length of the resulting subsequence (res).
  2. Iterate through the input array, starting from the third element.
  3. Compare the difference between the current element and the previous element with the previous difference (pre).
  4. If the signs of the differences alternate (i.e., one is positive and the other is negative), increment the length of the resulting subsequence.

Implement

    class Solution:
    def wiggleMaxLength(self, nums: List[int]) -> int:
      l = len(nums)
      if l < 2:
        return l
      pre = nums[1] - nums[0]
      res = 1 if pre == 0 else 2
      for i in range(2, l):
        dif = nums[i] - nums[i - 1]
        if (dif > 0 and pre <= 0) or (dif < 0 and pre >= 0):
          res += 1
          pre = dif
      return res