Longest subsequence such that difference between adjacents is one | Set 2 | function to find longest subsequence such that difference between adjacents is one ; hash table to map the array element with the length of the longest subsequence of which it is a part of and is the last element of that subsequence ; to store the longest length subsequence ; traverse the array elements ; initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in ' um ' and its length of subsequence is greater than ' len ' ; if ' arr [ i ] + 1' is in ' um ' and its length of subsequence is greater than ' len ' ; update arr [ i ] subsequence length in ' um ' ; update longest length ; required longest length subsequence ; Driver Code
function longLenSub ( arr , n ) { let um = new Map ( ) ; let longLen = 0 ; for ( let i = 0 ; i < n ; i ++ ) { let len = 0 ; if ( um . has ( arr [ i ] - 1 ) && len < um . get ( arr [ i ] - 1 ) ) len = um . get ( arr [ i ] - 1 ) ; if ( um . has ( arr [ i ] + 1 ) && len < um . get ( arr [ i ] + 1 ) ) len = um . get ( arr [ i ] + 1 ) ; um . set ( arr [ i ] , len + 1 ) ; if ( longLen < um . get ( arr [ i ] ) ) longLen = um . get ( arr [ i ] ) ; } return longLen ; } let arr = [ 1 , 2 , 3 , 4 , 5 , 3 , 2 ] ; let n = arr . length ; document . write ( " " + longLenSub ( arr , n ) ) ;