Maximum length subsequence with difference between adjacent elements as either 0 or 1 | function to find maximum length subsequence with difference between adjacent elements as either 0 or 1 ; Initialize mls [ ] values for all indexes ; Compute optimized maximum length subsequence values in bottom up manner ; Store maximum of all ' mls ' values in ' max ' ; required maximum length subsequence ; driver program
function maxLenSub ( arr , n ) { let mls = new Array ( n ) . fill ( 1 ) , max = 0 ; for ( let i = 0 ; i < n ; i ++ ) mls [ i ] = 1 ; for ( let i = 1 ; i < n ; i ++ ) for ( let j = 0 ; j < i ; j ++ ) if ( Math . abs ( arr [ i ] - arr [ j ] ) <= 1 && mls [ i ] < mls [ j ] + 1 ) mls [ i ] = mls [ j ] + 1 ; for ( let i = 0 ; i < n ; i ++ ) if ( max < mls [ i ] ) max = mls [ i ] ; return max ; } let arr = [ 2 , 5 , 6 , 3 , 7 , 6 , 5 , 8 ] ; let n = arr . length ; document . write ( " " + maxLenSub ( arr , n ) ) ;