Length of longest non | C ++ program to implement the above approach ; Function to find the longest non - decreasing subsequence with difference between adjacent elements exactly equal to 1 ; Base case ; Sort the array in ascending order ; Stores the maximum length ; Traverse the array ; If difference between current pair of adjacent elements is 1 or 0 ; Extend the current sequence Update len and max_len ; Otherwise , start a new subsequence ; Print the maximum length ; Driver Code ; Given array ; Size of the array ; Function call to find the longest subsequence
#include <bits/stdc++.h> NEW_LINE using namespace std ; void longestSequence ( int arr [ ] , int N ) { if ( N == 0 ) { cout << 0 ; return ; } sort ( arr , arr + N ) ; int maxLen = 1 ; int len = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] arr [ i ] == arr [ i - 1 ] + 1 ) { len ++ ; maxLen = max ( maxLen , len ) ; } else { len = 1 ; } } cout << maxLen ; } int main ( ) { int arr [ ] = { 8 , 5 , 4 , 8 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; longestSequence ( arr , N ) ; return 0 ; }