Longest Increasing consecutive subsequence | function that returns the length of the longest increasing subsequence whose adjacent element differ by 1 ; stores the index of elements ; stores the length of the longest subsequence that ends with a [ i ] ; iterate for all element ; if a [ i ] - 1 is present before i - th index ; last index of a [ i ] - 1 ; Driver Code
function longestSubsequence ( a , n ) { var mp = new Map ( ) ; var dp = Array ( n ) . fill ( 0 ) ; var maximum = - 1000000000 ; for ( var i = 0 ; i < n ; i ++ ) { if ( mp . has ( a [ i ] - 1 ) ) { var lastIndex = mp . get ( a [ i ] - 1 ) - 1 ; dp [ i ] = 1 + dp [ lastIndex ] ; } else dp [ i ] = 1 ; mp . set ( a [ i ] , i + 1 ) ; maximum = Math . max ( maximum , dp [ i ] ) ; } return maximum ; } var a = [ 3 , 10 , 3 , 11 , 4 , 5 , 6 , 7 , 8 , 12 ] ; var n = a . length ; document . write ( longestSubsequence ( a , n ) ) ;