Maximum length subsequence with difference between adjacent elements as either 0 or 1

link 0

Given an array of n integers. The problem is to find maximum length of the subsequence with difference between adjacent elements as either 0 or 1.

Examples:

Input : arr[] = {2, 5, 6, 3, 7, 6, 5, 8}
Output : 5
The subsequence is {5, 6, 7, 6, 5}.

Input : arr[] = {-2, -1, 5, -1, 4, 0, 3}
Output : 4
The subsequence is {-2, -1, -1, 0}.

The solution to this problem closely resembles the Longest Increasing Subsequence problem. The only difference is that here we have to check whether the absolute difference between the adjacent elements of the subsequence is either 0 or 1.

// C++ implementation to find maximum length
// subsequence with difference between adjacent
// elements as either 0 or 1
#include <bits/stdc++.h>
using namespace std;
// function to find maximum length subsequence
// with difference between adjacent elements as
// either 0 or 1
int maxLenSub(int arr[], int n)
{
    int mls[n], max = 0;
    
    // Initialize mls[] values for all indexes
    for (int i=0; i<n; i++)
        mls[i] = 1;
    
    // Compute optimized maximum length subsequence
    // values in bottom up manner
    for (int i=1; i<n; i++)
        for (int j=0; j<i; j++)
            if (abs(arr[i] - arr[j]) <= 1 &&
                    mls[i] < mls[j] + 1)
                mls[i] = mls[j] + 1;
    
    // Store maximum of all 'mls' values in 'max'   
    for (int i=0; i<n; i++)
        if (max < mls[i])
            max = mls[i];
    
    // required maximum length subsequence
    return max;       
}
// Driver program to test above
int main()
{
    int arr[] = {2, 5, 6, 3, 7, 6, 5, 8};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Maximum length subsequence = "
         << maxLenSub(arr, n);
    return 0;
}

Output:

Maximum length subsequence = 5

Time Complexity: O(n2)
Auxiliary Space: O(n)

Disclaimer: This content belongs to geeksforgeeks, source: http://geeksforgeeks.org

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar