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


We are given an array of any size and the task is to find the subsequence in the given array with the elements having difference between adjacent elements as 0 or 1.

Input − int arr[] = { 2, 1, 5, 6, 3, 4, 7, 6}

Output − Maximum length subsequence with difference between adjacent elements as either 0 or 1 is − 3

Explanation − The subsequence of adjacent elements in an array with difference as 0 or 1 are {2, 1}. Therefore, the maximum length of subsequence is 2.

Input − int arr[] = { 2, 1, 7, 6, 5}

Output − Maximum length subsequence with difference between adjacent elements as either 0 or 1 is − 3

Explanation − The adjacent elements in an array with difference as 0 or 1 is {7, 6, 5}.. Therefore, the maximum length of subsequence is 3.

Approach used in the below program is as follows

  • Input an array of type integers which can contain positive as well as negative elements.
  • Calculate the size of an array and pass an array and size to the function for further functionality.
  • Take a temporary array with same size of an input array let’s say temp[size] and another variable maximum and set it to 0
  • Start loop for from 0 till size of an array
  • Inside the loop, set temp[i] with 1
  • Start another loop, from 1 till size
  • Inside the loop, start another loop j from 0 till j less than i
  • Inside the loop, check if whether adjacent elements with difference 0 or 1 then set temp[i] with temp[i] + 1
  • Start loop for from 0 till size
  • Inside the loop, check if maximum is less than temp[i] then set maximum = temp[i]
  • Return maximum
  • Print the result

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//function to calculate the maximum difference
int maximum_adja(int arr[], int size){
   int temp[size], maximum = 0;
   for (int i=0; i<size; i++){
      temp[i] = 1;
   }
   for (int i=1; i<size; i++){
      for (int j=0; j<i; j++){
         if (abs(arr[i] - arr[j]) <= 1 && temp[i] < temp[j] + 1){
            temp[i] = temp[j] + 1;
         }
      }
   }
   for (int i=0; i<size; i++){
      if (maximum < temp[i]){
         maximum = temp[i];
      }
   }
   return maximum;
}
int main(){
   int arr[] = {1, 5, 3, 7, 8, 9, 2};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Maximum length subsequence with difference between adjacent elements as either 0
   or 1 is: "<<maximum_adja(arr, size);
   return 0;
}

Output

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

Updated on: 03-Aug-2020

687 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements