Given an integer array, find the length of the longest subsequence with alternate low and high elements in the array.

For example,

Input: nums[] = [8, 9, 6, 4, 5, 7, 3, 2, 4]
Output: 6
Explanation: There are several subsequences with alternate low and high elements having length 6:
 
[8, 9, 6, 7, 3, 4]
[8, 9, 6, 7, 2, 4]
[8, 9, 4, 7, 3, 4]
[8, 9, 4, 7, 2, 4]

Practice this problem

The idea is to traverse the array from left to right and keep track of the longest alternating sequence that ends at the element you are currently at. We update two counters, low and high, for each index in the array since the current element in the final maximum length alternating sequence can be either low or high. Now, we update high = low + 1 if the current element is greater than its previous element and update low = high + 1 if the current element is less than the previous element. Don’t update low or high if the current element is the same as the preceding element because the problem targets only subsequences, not subarrays.

 
Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

The length of the longest alternating subsequence is 6

Java


Download  Run Code

Output:

The length of the longest alternating subsequence is 6

Python


Download  Run Code

Output:

The length of the longest alternating subsequence is 6

The time complexity of the above solution is O(n) and requires O(1) extra space, where n is the length of the array.

 
Because of the way this algorithm uses optimal substructure (the longest alternating sequence ending at each position is calculated merely from a related but smaller and overlapping subproblem: the longest alternating sequence ending at the previous position), this algorithm can be viewed as a simple example of dynamic programming.