{x}
blog image

Wiggle Subsequence

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 1:

Input: nums = [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).

Example 2:

Input: nums = [1,17,5,10,13,15,10,5,16,8]
Output: 7
Explanation: There are several subsequences that achieve this length.
One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).

Example 3:

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

 

Constraints:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000

 

Follow up: Could you solve this in O(n) time?

Solution Explanation: 376. Wiggle Subsequence

This problem asks for the length of the longest wiggle subsequence within a given integer array nums. A wiggle sequence is defined as a sequence where the differences between consecutive numbers strictly alternate between positive and negative.

Approach 1: Dynamic Programming (O(n^2) Time Complexity)

This approach utilizes dynamic programming to find the solution. We maintain two arrays, f and g, where:

  • f[i] represents the length of the longest wiggle subsequence ending at index i with an upward trend (i.e., the last difference was positive).
  • g[i] represents the length of the longest wiggle subsequence ending at index i with a downward trend (i.e., the last difference was negative).

The algorithm iterates through the nums array. For each element nums[i], it considers all previous elements nums[j] (where j < i):

  • If nums[j] < nums[i], it means we can extend a downward trend to an upward trend. We update f[i] as max(f[i], g[j] + 1).
  • If nums[j] > nums[i], it means we can extend an upward trend to a downward trend. We update g[i] as max(g[i], f[j] + 1).

The final answer is the maximum of all f[i] and g[i] values.

Time Complexity: O(n^2) due to the nested loops iterating through all pairs of elements.

Space Complexity: O(n) to store the f and g arrays.

Code Implementations

The code implementations below reflect the dynamic programming approach. They are provided in multiple languages:

Python3

class Solution:
    def wiggleMaxLength(self, nums: List[int]) -> int:
        n = len(nums)
        ans = 1
        f = [1] * n
        g = [1] * n
        for i in range(1, n):
            for j in range(i):
                if nums[j] < nums[i]:
                    f[i] = max(f[i], g[j] + 1)
                elif nums[j] > nums[i]:
                    g[i] = max(g[i], f[j] + 1)
            ans = max(ans, f[i], g[i])
        return ans
 

Java

class Solution {
    public int wiggleMaxLength(int[] nums) {
        int n = nums.length;
        int ans = 1;
        int[] f = new int[n];
        int[] g = new int[n];
        Arrays.fill(f, 1);
        Arrays.fill(g, 1);
        for (int i = 1; i < n; ++i) {
            for (int j = 0; j < i; ++j) {
                if (nums[j] < nums[i]) {
                    f[i] = Math.max(f[i], g[j] + 1);
                } else if (nums[j] > nums[i]) {
                    g[i] = Math.max(g[i], f[j] + 1);
                }
            }
            ans = Math.max(ans, Math.max(f[i], g[i]));
        }
        return ans;
    }
}

C++

class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        int n = nums.size();
        int ans = 1;
        vector<int> f(n, 1);
        vector<int> g(n, 1);
        for (int i = 1; i < n; ++i) {
            for (int j = 0; j < i; ++j) {
                if (nums[j] < nums[i]) {
                    f[i] = max(f[i], g[j] + 1);
                } else if (nums[j] > nums[i]) {
                    g[i] = max(g[i], f[j] + 1);
                }
            }
            ans = max({ans, f[i], g[i]});
        }
        return ans;
    }
};

Go

func wiggleMaxLength(nums []int) int {
	n := len(nums)
	f := make([]int, n)
	g := make([]int, n)
	for i := range f {
		f[i] = 1
		g[i] = 1
	}
	ans := 1
	for i := 1; i < n; i++ {
		for j := 0; j < i; j++ {
			if nums[j] < nums[i] {
				f[i] = max(f[i], g[j]+1)
			} else if nums[j] > nums[i] {
				g[i] = max(g[i], f[j]+1)
			}
		}
		ans = max(ans, max(f[i], g[i]))
	}
	return ans
}
 
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

TypeScript

function wiggleMaxLength(nums: number[]): number {
    const n = nums.length;
    const f: number[] = new Array(n).fill(1);
    const g: number[] = new Array(n).fill(1);
    let ans = 1;
    for (let i = 1; i < n; ++i) {
        for (let j = 0; j < i; ++j) {
            if (nums[j] < nums[i]) {
                f[i] = Math.max(f[i], g[j] + 1);
            } else if (nums[j] > nums[i]) {
                g[i] = Math.max(g[i], f[j] + 1);
            }
        }
        ans = Math.max(ans, Math.max(f[i], g[i]));
    }
    return ans;
}

These code snippets all implement the same dynamic programming algorithm, but in different programming languages. Note that there are more efficient O(n) solutions, but this dynamic programming approach clearly illustrates the logic.