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 to test above
def maxLenSub ( arr , n ) : NEW_LINE INDENT mls = [ ] NEW_LINE max = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mls . append ( 1 ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( abs ( arr [ i ] - arr [ j ] ) <= 1 and mls [ i ] < mls [ j ] + 1 ) : NEW_LINE INDENT mls [ i ] = mls [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT ' NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( max < mls [ i ] ) : NEW_LINE INDENT max = mls [ i ] NEW_LINE DEDENT DEDENT return max NEW_LINE DEDENT arr = [ 2 , 5 , 6 , 3 , 7 , 6 , 5 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum ▁ length ▁ subsequence ▁ = ▁ " , maxLenSub ( arr , n ) ) NEW_LINE