Longest alternating subsequence

Last Updated : 14 Apr, 2026

A sequence {X1, X2, …, Xn} is called alternating if its elements strictly alternate between increasing and decreasing. Formally, it must satisfy either of the following patterns:

  • Up–down pattern:
    X1 < X2 > X3 < X4 > X5 < …
  • Down–up pattern:
    X1 > X2 < X3 > X4 < X5 > …

Examples:

Input: arr[] = {1, 5, 4}
Output: 3
Explanation: The array is of the form  x1 < x2 > x3, hence the complete array forms an alternating sequence.

Input: arr[] = {10, 22, 9, 33, 49, 50, 31, 60}
Output: 6
Explanation: The subsequences {10, 22, 9, 33, 31, 60} and {10, 22, 9, 49, 31, 60} and {10, 22, 9, 50, 31, 60} all are longest subsequence of length 6.

Try It Yourself
redirect icon

[Naive Approach] Using Recursion - O(n(n+1)) Time and Linear Space

The idea is to treat every index in the array as the ending point of a potential alternating subsequence. An alternating subsequence is one where the comparisons between consecutive elements keep switching between:

  • up -> down -> up -> down -> …, or
  • down -> up -> down -> up -> …

To enforce this alternating pattern, we use a parameter inc, which tells us what the expected direction is for the next comparison.

  • inc = 1 - The next element to be included in the subsequence should be increasing(i.e., arr[next] > arr[current])
  • inc = 0 - The next element to be included in the subsequence should be decreasing(i.e., arr[next] < arr[current])
C++
//Driver Code Starts
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

//Driver Code Ends

int lasEndingAtIndex(vector<int>& arr, int idx, int inc) {

    // Base case
    if (idx == 0)
        return 1;

    // Consider all elements on the left of i,
    // recursively compute LASs ending with 
    // them and consider the largest
    int maxLen = 1;
    for (int prev = 0; prev < idx; prev++) {

        // currently the sequence is decreasing
        if (inc == 0 && arr[prev] > arr[idx]) {
            int len = lasEndingAtIndex(arr, prev, 1 - inc);
            maxLen = max(maxLen, len + 1);
        }
        
        // currently the sequence is increasing
        else if (inc == 1 && arr[prev] < arr[idx]) {
            int len = lasEndingAtIndex(arr, prev, 1 - inc);
            maxLen = max(maxLen, len + 1);
        }
    }

    return maxLen;
}

int alternatingMaxLength(vector<int>& arr) {
    int n = arr.size();

    // because arr length >= 1 
    // and any subsequence of 
    // length 1 is an LAS
    int res = 1;

    // for each subsequence ending
    // with index i
    for (int i = 1; i < n; i++) {

        // checking for both possibilities
        // up-down pattern, down-up pattern
        res = max(res, lasEndingAtIndex(arr, i, 0));
        res = max(res, lasEndingAtIndex(arr, i, 1));
    }

    return res;
}

//Driver Code Starts

int main() {
    vector<int> arr = {10, 22, 9, 33, 49, 50, 31, 60};
    cout << alternatingMaxLength(arr);
}

//Driver Code Ends
Java
//Driver Code Starts
class GFG {
//Driver Code Ends

    static int lasEndingAtIndex(int[] arr, int idx, int inc) {
      
        // Base case
        if (idx == 0)
            return 1;

        // Consider all elements on the left of i,
        // recursively compute LASs ending with 
        // them and consider the largest
        int maxLen = 1;
        for (int prev = 0; prev < idx; prev++) {
            
            // currently the sequence is decreasing
            if (inc == 0 && arr[prev] > arr[idx]) {
                int len = lasEndingAtIndex(arr, prev, 1-inc);
                maxLen = Math.max(maxLen,  len + 1);
            }
            
            // currently the sequence is increasing
            else if(inc == 1 && arr[prev] < arr[idx]) {
                int len = lasEndingAtIndex(arr, prev, 1-inc);
                maxLen = Math.max(maxLen,  len + 1);
            }
        }
                
        return maxLen;
    }

    static int alternatingMaxLength(int[] arr) {
        int n = arr.length;
        
        // because arr length >= 1 
        // and any subsequence of 
        // length 1 is an LAS
        int res = 1;
        
        // for each subsequence ending
        // with index i
        for (int i = 1; i < n; i++) {
            
            // checking for both possibilities
            // up-down pattern, down-up pattern
            res = Math.max(res, lasEndingAtIndex(arr, i, 0));
            res = Math.max(res, lasEndingAtIndex(arr, i, 1));
        }
        return res;
    }

//Driver Code Starts

    public static void main(String[] args) {
        int[] arr = {10, 22, 9, 33, 49, 50, 31, 60};
        System.out.println(alternatingMaxLength(arr));
    }
}
//Driver Code Ends
Python
def lasEndingAtIndex(arr, idx, inc):

    # Base case
    if idx == 0:
        return 1

    # Consider all elements on the left of i,
    # recursively compute LASs ending with 
    # them and consider the largest
    maxLen = 1
    for prev in range(idx):

        # currently the sequence is decreasing
        if inc == 0 and arr[prev] > arr[idx]:
            length = lasEndingAtIndex(arr, prev, 1 - inc)
            maxLen = max(maxLen, length + 1)
            
            
        # currently the sequence is increasing
        elif inc == 1 and arr[prev] < arr[idx]:
            length = lasEndingAtIndex(arr, prev, 1 - inc)
            maxLen = max(maxLen, length + 1)

    return maxLen


def alternatingMaxLength(arr):
    n = len(arr)

    # because arr length >= 1 
    # and any subsequence of 
    # length 1 is an LAS
    res = 1

    # for each subsequence ending
    # with index i
    for i in range(1, n):

        # checking for both possibilities
        # up-down pattern, down-up pattern
        res = max(res, lasEndingAtIndex(arr, i, 0))
        res = max(res, lasEndingAtIndex(arr, i, 1))

    return res


#Driver Code Starts

if __name__ == "__main__":
    arr = [10, 22, 9, 33, 49, 50, 31, 60]
    print(alternatingMaxLength(arr))
#Driver Code Ends
C#
//Driver Code Starts
using System;

class GFG {
//Driver Code Ends

    static int lasEndingAtIndex(int[] arr, int idx, int inc) {

        // Base case
        if (idx == 0)
            return 1;

        // Consider all elements on the left of i,
        // recursively compute LASs ending with 
        // them and consider the largest
        int maxLen = 1;
        for (int prev = 0; prev < idx; prev++) {

            // currently the sequence is decreasing
            if (inc == 0 && arr[prev] > arr[idx]) {
                int len = lasEndingAtIndex(arr, prev, 1 - inc);
                maxLen = Math.Max(maxLen, len + 1);
            }
            
            
            // currently the sequence is increasing
            else if (inc == 1 && arr[prev] < arr[idx]) {
                int len = lasEndingAtIndex(arr, prev, 1 - inc);
                maxLen = Math.Max(maxLen, len + 1);
            }
        }

        return maxLen;
    }

    static int alternatingMaxLength(int[] arr) {
        int n = arr.Length;

        // because arr length >= 1 
        // and any subsequence of 
        // length 1 is an LAS
        int res = 1;

        // for each subsequence ending
        // with index i
        for (int i = 1; i < n; i++) {

            // checking for both possibilities
            // up-down pattern, down-up pattern
            res = Math.Max(res, lasEndingAtIndex(arr, i, 0));
            res = Math.Max(res, lasEndingAtIndex(arr, i, 1));
        }

        return res;
    }

//Driver Code Starts

    public static void Main(string[] args) {
        int[] arr = {10, 22, 9, 33, 49, 50, 31, 60};
        Console.WriteLine(alternatingMaxLength(arr));
    }
}
//Driver Code Ends
JavaScript
function lasEndingAtIndex(arr, idx, inc) {

    // Base case
    if (idx === 0)
        return 1;

    // Consider all elements on the left of i,
    // recursively compute LASs ending with 
    // them and consider the largest
    let maxLen = 1;
    for (let prev = 0; prev < idx; prev++) {
        
        // currently the sequence is decreasing
        if (inc === 0 && arr[prev] > arr[idx]) {
            let len = lasEndingAtIndex(arr, prev, 1 - inc);
            maxLen = Math.max(maxLen, len + 1);
        }
        
        // currently the sequence is increasing
        else if (inc === 1 && arr[prev] < arr[idx]) {
            let len = lasEndingAtIndex(arr, prev, 1 - inc);
            maxLen = Math.max(maxLen, len + 1);
        }
    }

    return maxLen;
}

function alternatingMaxLength(arr) {
    let n = arr.length;

    // because arr length >= 1 
    // and any subsequence of 
    // length 1 is an LAS
    let res = 1;

    // for each subsequence ending
    // with index i
    for (let i = 1; i < n; i++) {

        // checking for both possibilities
        // up-down pattern, down-up pattern
        res = Math.max(res, lasEndingAtIndex(arr, i, 0));
        res = Math.max(res, lasEndingAtIndex(arr, i, 1));
    }

    return res;
}


//Driver Code Starts
// Driver code
let arr = [10, 22, 9, 33, 49, 50, 31, 60];
console.log(alternatingMaxLength(arr));
//Driver Code Ends

Output
6

[Better Approach - 1] Using Memoization - O(n2) Time and O(n) Space

In the recursive solution, each index idx tries to build the LAS ending at that position by checking all previous indices. Many of these recursive calls repeat—for example, the LAS for the same (prev, inc) is needed multiple times for different idx values.
To avoid recomputing these overlapping subproblems, we store results in dp[idx][inc]. Once a state is computed, it is reused, ensuring each (idx, inc) pair is solved only once.
This memoization removes exponential repetition and reduces the overall time complexity to O(n²).

C++
//Driver Code Starts
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

//Driver Code Ends

int lasEndingAtIndex(int idx, int inc, vector<int>& arr, vector<vector<int>>& dp) {

    // Base case
    if (idx == 0)
        return 1;

    if (dp[idx][inc] != -1)
        return dp[idx][inc];

    // Consider all elements on the left of i,
    // recursively compute LASs ending with 
    // them and consider the largest
    int maxLen = 1;
    for (int prev = 0; prev < idx; prev++) {

        if ((inc == 0 && arr[prev] > arr[idx]) ||
            (inc == 1 && arr[prev] < arr[idx])) {

            int len = lasEndingAtIndex(prev, 1 - inc, arr, dp);
            maxLen = max(maxLen, len + 1);
        }
    }

    return dp[idx][inc] = maxLen;
}

int alternatingMaxLength(vector<int>& arr) {
    int n = arr.size();

    vector<vector<int>> dp(n, vector<int>(2, -1));

    // because arr length >= 1 
    // and any subsequence of 
    // length 1 is an LAS
    int res = 1;

    // for each subsequence ending
    // with index i
    for (int i = 1; i < n; i++) {

        // checking for both possibilities
        // up-down pattern, down-up pattern
        res = max(res, lasEndingAtIndex(i, 0, arr, dp));
        res = max(res, lasEndingAtIndex(i, 1, arr, dp));
    }

    return res;
}

//Driver Code Starts

int main() {
    vector<int> arr = {10, 22, 9, 33, 49, 50, 31, 60};
    cout << alternatingMaxLength(arr);
}

//Driver Code Ends
Java
//Driver Code Starts
import java.util.Arrays;

class GFG {
//Driver Code Ends

    static int lasEndingAtIndex(int idx, int inc, int[] arr, int[][] dp) {
      
        // Base case
        if (idx == 0)
            return 1;
            
        if( dp[idx][inc] != -1 ) 
            return dp[idx][inc];

        // Consider all elements on the left of i,
        // recursively compute LASs ending with 
        // them and consider the largest
        int maxLen = 1;
        for (int prev = 0; prev < idx; prev++) {
            
            if ((inc == 0 && arr[prev] > arr[idx]) ||
                (inc == 1 && arr[prev] < arr[idx])) {
                int len = lasEndingAtIndex(prev, 1-inc, arr, dp);
                maxLen = Math.max(maxLen,  len + 1);
            }
        }
                
        return dp[idx][inc] = maxLen;
    }

    static int alternatingMaxLength(int[] arr) {
        int n = arr.length;
        
        int[][] dp = new int[n][2];
        
        // Initialising dp array with invalid values
        for( int[] dp1 : dp ) 
            Arrays.fill(dp1, -1);
            
            
        // because arr length >= 1 
        // and any subsequence of 
        // length 1 is an LAS
        int res = 1;
        
        // for each subsequence ending
        // with index i
        for (int i = 1; i < n; i++) {
            
            // checking for both possibilities
            // up-down pattern, down-up pattern
            res = Math.max(res, lasEndingAtIndex(i, 0, arr, dp));
            res = Math.max(res, lasEndingAtIndex(i, 1, arr, dp));
        }
        return res;
    }

//Driver Code Starts

    public static void main(String[] args) {
        int[] arr = {10, 22, 9, 33, 49, 50, 31, 60};
        System.out.println(alternatingMaxLength(arr));
    }
}
//Driver Code Ends
Python
def lasEndingAtIndex(idx, inc, arr, dp):

    # Base case
    if idx == 0:
        return 1

    if dp[idx][inc] != -1:
        return dp[idx][inc]

    # Consider all elements on the left of i,
    # recursively compute LASs ending with 
    # them and consider the largest
    maxLen = 1
    for prev in range(idx):

        if (inc == 0 and arr[prev] > arr[idx]) or \
           (inc == 1 and arr[prev] < arr[idx]):

            length = lasEndingAtIndex(prev, 1 - inc, arr, dp)
            maxLen = max(maxLen, length + 1)

    dp[idx][inc] = maxLen
    return maxLen


def alternatingMaxLength(arr):
    n = len(arr)

    dp = [[-1, -1] for _ in range(n)]

    # because arr length >= 1 
    # and any subsequence of 
    # length 1 is an LAS
    res = 1

    # for each subsequence ending
    # with index i
    for i in range(1, n):

        # checking for both possibilities
        # up-down pattern, down-up pattern
        res = max(res, lasEndingAtIndex(i, 0, arr, dp))
        res = max(res, lasEndingAtIndex(i, 1, arr, dp))

    return res


#Driver Code Starts
if __name__ == "__main__":
    arr = [10, 22, 9, 33, 49, 50, 31, 60]
    print(alternatingMaxLength(arr))

#Driver Code Ends
C#
//Driver Code Starts
using System;

class GFG {
//Driver Code Ends

    static int lasEndingAtIndex(int idx, int inc, int[] arr, int[][] dp) {

        // Base case
        if (idx == 0)
            return 1;

        if (dp[idx][inc] != -1)
            return dp[idx][inc];

        // Consider all elements on the left of i,
        // recursively compute LASs ending with 
        // them and consider the largest
        int maxLen = 1;
        for (int prev = 0; prev < idx; prev++) {

            if ((inc == 0 && arr[prev] > arr[idx]) ||
                (inc == 1 && arr[prev] < arr[idx])) {

                int len = lasEndingAtIndex(prev, 1 - inc, arr, dp);
                maxLen = Math.Max(maxLen, len + 1);
            }
        }

        return dp[idx][inc] = maxLen;
    }

    static int alternatingMaxLength(int[] arr) {
        int n = arr.Length;

        int[][] dp = new int[n][];
        for (int i = 0; i < n; i++)
            dp[i] = new int[] { -1, -1 };

        // because arr length >= 1 
        // and any subsequence of 
        // length 1 is an LAS
        int res = 1;

        // for each subsequence ending
        // with index i
        for (int i = 1; i < n; i++) {

            // checking for both possibilities
            // up-down pattern, down-up pattern
            res = Math.Max(res, lasEndingAtIndex(i, 0, arr, dp));
            res = Math.Max(res, lasEndingAtIndex(i, 1, arr, dp));
        }

        return res;
    }


//Driver Code Starts
    public static void Main(string[] args) {
        int[] arr = {10, 22, 9, 33, 49, 50, 31, 60};
        Console.WriteLine(alternatingMaxLength(arr));
    }
}
//Driver Code Ends
JavaScript
function lasEndingAtIndex(idx, inc, arr, dp) {

    // Base case
    if (idx === 0)
        return 1;

    if (dp[idx][inc] !== -1)
        return dp[idx][inc];

    // Consider all elements on the left of i,
    // recursively compute LASs ending with 
    // them and consider the largest
    let maxLen = 1;
    for (let prev = 0; prev < idx; prev++) {

        if ((inc === 0 && arr[prev] > arr[idx]) ||
            (inc === 1 && arr[prev] < arr[idx])) {

            let len = lasEndingAtIndex(prev, 1 - inc, arr, dp);
            maxLen = Math.max(maxLen, len + 1);
        }
    }

    return dp[idx][inc] = maxLen;
}

function alternatingMaxLength(arr) {
    let n = arr.length;

    let dp = Array.from({ length: n }, () => [-1, -1]);

    // because arr length >= 1 
    // and any subsequence of 
    // length 1 is an LAS
    let res = 1;

    // for each subsequence ending
    // with index i
    for (let i = 1; i < n; i++) {

        // checking for both possibilities
        // up-down pattern, down-up pattern
        res = Math.max(res, lasEndingAtIndex(i, 0, arr, dp));
        res = Math.max(res, lasEndingAtIndex(i, 1, arr, dp));
    }

    return res;
}


//Driver Code Starts
// Driver code
let arr = [10, 22, 9, 33, 49, 50, 31, 60];
console.log(alternatingMaxLength(arr));
//Driver Code Ends

Output
6

[Better Approach - 2] Using DP (Bottom Up Tabulation) - O(n2) Time and O(n) Space

This DP solution computes the longest alternating subsequence ending at each index. For every idx, we check all earlier positions prev < idx. If the required direction (inc) matches the comparison between arr[prev] and arr[idx], we extend the LAS ending at prev by doing:
dp[idx][inc] = dp[prev][1 - inc] + 1

Because all smaller indices are already processed, each dp[idx][inc] is correct when computed. The answer is the maximum LAS length formed at any index and direction.

C++
//Driver Code Starts
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

//Driver Code Ends

int alternatingMaxLength(vector<int>& arr) {
    int n = arr.size();

    vector<vector<int>> dp(n, vector<int>(2, 0));

    // any subsequence of length 1 is an LIS
    int ans = 1;

    // base cases
    dp[0][0] = 1;
    dp[0][1] = 1;

    // for each subsequence ending
    // with index i
    for (int idx = 1; idx < n; idx++) {

        dp[idx][0] = 1;
        dp[idx][1] = 1;

        // Consider all elements on the left of i,
        // compute LASs ending with them and extend 
        // them to contain index i if possible
        for (int prev = 0; prev < idx; prev++) {
            for (int inc = 0; inc <= 1; inc++) {

                if ((inc == 0 && arr[prev] > arr[idx]) ||
                    (inc == 1 && arr[prev] < arr[idx])) {

                    int len = dp[prev][1 - inc];
                    dp[idx][inc] = max(dp[idx][inc], len + 1);
                    ans = max(ans, dp[idx][inc]);
                }
            }
        }
    }

    return ans;
}

//Driver Code Starts

int main() {
    vector<int> arr = {10, 22, 9, 33, 49, 50, 41, 60};
    cout << alternatingMaxLength(arr);
}

//Driver Code Ends
Java
//Driver Code Starts
import java.util.Arrays;

class GFG {
//Driver Code Ends

    static int alternatingMaxLength(int arr[]) {
        int n = arr.length;
        
        int[][] dp = new int[n][2];
        
        // any subsequence of length 1 is an LIS
        int ans = 1;
        
        // base cases
        dp[0][0] = 1;
        dp[0][1] = 1;
        
        // for each subsequence ending
        // with index i
        for (int idx = 1; idx < n; idx++) {
            
            // Consider all elements on the left of i,
            // compute LASs ending with them and extend 
            // them to contain index i if possible
            for (int prev = 0; prev < idx; prev++) {
                for( int inc = 0; inc <= 1; inc++ ) {
                    
                    if ((inc == 0 && arr[prev] > arr[idx]) ||
                        (inc == 1 && arr[prev] < arr[idx])) {
                        int len = dp[prev][1-inc];
                        dp[idx][inc] = Math.max(dp[idx][inc],  len + 1);
                        ans = Math.max(ans, dp[idx][inc]);
                    }
                }
            }
        }
        return ans;
    }

//Driver Code Starts

    public static void main(String args[]) {
        int arr[] = {10, 22, 9, 33, 49, 50, 41, 60};
        System.out.println(alternatingMaxLength(arr));
    }
}

//Driver Code Ends
Python
def alternatingMaxLength(arr):
    n = len(arr)

    dp = [[0, 0] for _ in range(n)]

    # any subsequence of length 1 is an LIS
    ans = 1

    # base cases
    dp[0][0] = 1
    dp[0][1] = 1

    # for each subsequence ending
    # with index i
    for idx in range(1, n):

        dp[idx][0] = 1
        dp[idx][1] = 1

        # Consider all elements on the left of i,
        # compute LASs ending with them and extend 
        # them to contain index i if possible
        for prev in range(idx):
            for inc in range(2):

                if (inc == 0 and arr[prev] > arr[idx]) or \
                   (inc == 1 and arr[prev] < arr[idx]):

                    length = dp[prev][1 - inc]
                    dp[idx][inc] = max(dp[idx][inc], length + 1)
                    ans = max(ans, dp[idx][inc])

    return ans


#Driver Code Starts
if __name__ == '__main__':
    arr = [10, 22, 9, 33, 49, 50, 41, 60]
    print(alternatingMaxLength(arr))
#Driver Code Ends
C#
//Driver Code Starts
using System;

class GFG {

//Driver Code Ends

    static int alternatingMaxLength(int[] arr) {
        int n = arr.Length;

        int[][] dp = new int[n][];
        for (int i = 0; i < n; i++)
            dp[i] = new int[2];

        // any subsequence of length 1 is an LIS
        int ans = 1;

        // base cases
        dp[0][0] = 1;
        dp[0][1] = 1;

        // for each subsequence ending
        // with index i
        for (int idx = 1; idx < n; idx++) {

            dp[idx][0] = 1;
            dp[idx][1] = 1;

            // Consider all elements on the left of i,
            // compute LASs ending with them and extend 
            // them to contain index i if possible
            for (int prev = 0; prev < idx; prev++) {
                for (int inc = 0; inc <= 1; inc++) {

                    if ((inc == 0 && arr[prev] > arr[idx]) ||
                        (inc == 1 && arr[prev] < arr[idx])) {

                        int len = dp[prev][1 - inc];
                        dp[idx][inc] = Math.Max(dp[idx][inc], len + 1);
                        ans = Math.Max(ans, dp[idx][inc]);
                    }
                }
            }
        }

        return ans;
    }

//Driver Code Starts

    public static void Main(string[] args) {
        int[] arr = {10, 22, 9, 33, 49, 50, 41, 60};
        Console.WriteLine(alternatingMaxLength(arr));
    }
}
//Driver Code Ends
JavaScript
function alternatingMaxLength(arr) {
    let n = arr.length;

    let dp = Array.from({ length: n }, () => [0, 0]);

    // any subsequence of length 1 is an LIS
    let ans = 1;

    // base cases
    dp[0][0] = 1;
    dp[0][1] = 1;

    // for each subsequence ending
    // with index i
    for (let idx = 1; idx < n; idx++) {

        dp[idx][0] = 1;
        dp[idx][1] = 1;

        // Consider all elements on the left of i,
        // compute LASs ending with them and extend 
        // them to contain index i if possible
        for (let prev = 0; prev < idx; prev++) {
            for (let inc = 0; inc <= 1; inc++) {

                if ((inc === 0 && arr[prev] > arr[idx]) ||
                    (inc === 1 && arr[prev] < arr[idx])) {

                    let len = dp[prev][1 - inc];
                    dp[idx][inc] = Math.max(dp[idx][inc], len + 1);
                    ans = Math.max(ans, dp[idx][inc]);
                }
            }
        }
    }

    return ans;
}


//Driver Code Starts
// Driver code
let arr = [10, 22, 9, 33, 49, 50, 41, 60];
console.log(alternatingMaxLength(arr));

//Driver Code Ends

Output
6

[Expected Approach] - Using Greedy Approach - O(n) Time and O(1) Space

This approach keeps track of two values at every step:

  • inc → the length of the longest alternating subsequence that last ended with a down step, meaning the next required element must be larger
  • dec → the length of the longest alternating subsequence that last ended with an up step, meaning the next required element must be smaller

As we scan the array:

  • If the current element is greater than the previous one, we can extend the subsequence that was expecting an increase—which is the one represented by dec.
    So we update: inc = dec + 1
  • If the current element is smaller than the previous one, we extend the subsequence that was expecting a decrease—represented by inc.
    So we update: dec = inc + 1

By the end, inc stores the best subsequence ending with a down pattern, and dec stores the best subsequence ending with an up pattern. The answer is the maximum of these two.

C++
//Driver Code Starts
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

//Driver Code Ends

int alternatingMaxLength(vector<int>& arr) {
    int n = arr.size();

    // inc and dec initialized as 1,
    // as single element is still LAS
    int inc = 1;
    int dec = 1;

    // Iterate from second element
    for (int i = 1; i < n; i++) {

        // extend the subsequence with last 
        // pair of elements as decreasing
        if (arr[i] > arr[i - 1]) {
            inc = dec + 1;
        }

        // extend the subsequence with last 
        // pair of elements as increasing
        else if (arr[i] < arr[i - 1]) {
            dec = inc + 1;
        }
    }

    // Return the maximum length
    return max(inc, dec);
}

//Driver Code Starts

int main() {
    vector<int> arr = {10, 22, 9, 33, 49, 50, 31, 60};
    cout << alternatingMaxLength(arr);
}
//Driver Code Ends
Java
//Driver Code Starts
class GFG {

//Driver Code Ends

    static int alternatingMaxLength(int[] arr) {
        int n = arr.length;

        // inc and dec initialized as 1,
        // as single element is still LAS
        int inc = 1;
        int dec = 1;

        // Iterate from second element
        for (int i = 1; i < n; i++) {
            
            // extend the subsequence with last 
            // pair of elements as decreasing
            if (arr[i] > arr[i - 1]) {
                inc = dec + 1;
            }
            
            // extend the subsequence with last 
            // pair of elements as increasing
            else if (arr[i] < arr[i - 1]) {
                dec = inc + 1;
            }
        }

        // Return the maximum length
        return Math.max(inc, dec);
    }

//Driver Code Starts
    public static void main(String[] args) {
        int[] arr = {10, 22, 9, 33, 49, 50, 31, 60};
        
        System.out.println(alternatingMaxLength(arr));
    }
}
//Driver Code Ends
Python
def alternatingMaxLength(arr):
    n = len(arr)

    # inc and dec initialized as 1,
    # as single element is still LAS
    inc = 1
    dec = 1

    # Iterate from second element
    for i in range(1, n):

        # extend the subsequence with last 
        # pair of elements as decreasing
        if arr[i] > arr[i - 1]:
            inc = dec + 1

        # extend the subsequence with last 
        # pair of elements as increasing
        elif arr[i] < arr[i - 1]:
            dec = inc + 1

    # Return the maximum length
    return max(inc, dec)


#Driver Code Starts
if __name__ == "__main__":
    arr = [10, 22, 9, 33, 49, 50, 31, 60]
    print(alternatingMaxLength(arr))
#Driver Code Ends
C#
//Driver Code Starts
using System;

class GFG {

//Driver Code Ends

    static int alternatingMaxLength(int[] arr) {
        int n = arr.Length;

        // inc and dec initialized as 1,
        // as single element is still LAS
        int inc = 1;
        int dec = 1;

        // Iterate from second element
        for (int i = 1; i < n; i++) {

            // extend the subsequence with last 
            // pair of elements as decreasing
            if (arr[i] > arr[i - 1]) {
                inc = dec + 1;
            }

            // extend the subsequence with last 
            // pair of elements as increasing
            else if (arr[i] < arr[i - 1]) {
                dec = inc + 1;
            }
        }

        // Return the maximum length
        return Math.Max(inc, dec);
    }

//Driver Code Starts

    public static void Main(string[] args) {
        int[] arr = {10, 22, 9, 33, 49, 50, 31, 60};
        Console.WriteLine(alternatingMaxLength(arr));
    }
}
//Driver Code Ends
JavaScript
function alternatingMaxLength(arr) {
    let n = arr.length;

    // inc and dec initialized as 1,
    // as single element is still LAS
    let inc = 1;
    let dec = 1;

    // Iterate from second element
    for (let i = 1; i < n; i++) {

        // extend the subsequence with last 
        // pair of elements as decreasing
        if (arr[i] > arr[i - 1]) {
            inc = dec + 1;
        }

        // extend the subsequence with last 
        // pair of elements as increasing
        else if (arr[i] < arr[i - 1]) {
            dec = inc + 1;
        }
    }

    // Return the maximum length
    return Math.max(inc, dec);
}


//Driver Code Starts
// Driver code
let arr = [10, 22, 9, 33, 49, 50, 31, 60];
console.log(alternatingMaxLength(arr));

//Driver Code Ends

Output
6
Comment