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 Code
< ? php function maxLenSub ( $ arr , $ n ) { $ mls = array ( ) ; $ max = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ mls [ $ i ] = 1 ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) for ( $ j = 0 ; $ j < $ i ; $ j ++ ) if ( abs ( $ arr [ $ i ] - $ arr [ $ j ] ) <= 1 and $ mls [ $ i ] < $ mls [ $ j ] + 1 ) $ mls [ $ i ] = $ mls [ $ j ] + 1 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) if ( $ max < $ mls [ $ i ] ) $ max = $ mls [ $ i ] ; return $ max ; } $ arr = array ( 2 , 5 , 6 , 3 , 7 , 6 , 5 , 8 ) ; $ n = count ( $ arr ) ; echo " Maximum ▁ length ▁ subsequence ▁ = ▁ " , maxLenSub ( $ arr , $ n ) ; ? >