Length of longest non | 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 ; Given array ; Size of the array ; Function call to find the longest subsequence
function longestSequence ( arr , N ) { if ( N == 0 ) { document . write ( 0 ) ; return ; } arr . sort ( ) ; var maxLen = 1 ; var len = 1 ; var i ; for ( i = 1 ; i < N ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] arr [ i ] == arr [ i - 1 ] + 1 ) { len ++ ; maxLen = Math . max ( maxLen , len ) ; } else { len = 1 ; } } document . write ( maxLen ) ; } var arr = [ 8 , 5 , 4 , 8 , 4 ] ; var N = arr . length ; longestSequence ( arr , N ) ;