Longest subsequence having difference atmost K | Function to find the longest Special Sequence ; Creating a list with all 0 's of size  equal to the length of String ; Supporting list with all 0 's of size 26 since  the given String consists  of only lower case alphabets ; Converting the ascii value to list indices ; Determining the lower bound ; Determining the upper bound ; Filling the dp array with values ; Filling the max_length array with max length of subsequence till now ; return the max length of subsequence ; Driver Code
function longest_subseq ( n , k , s ) { let dp = new Array ( n ) ; let max_length = new Array ( 26 ) ; for ( let i = 0 ; i < 26 ; i ++ ) { max_length [ i ] = 0 ; dp [ i ] = 0 ; } for ( let i = 0 ; i < n ; i ++ ) { let curr = s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; let lower = Math . max ( 0 , curr - k ) ; let upper = Math . min ( 25 , curr + k ) ; for ( let j = lower ; j < upper + 1 ; j ++ ) { dp [ i ] = Math . max ( dp [ i ] , max_length [ j ] + 1 ) ; } max_length [ curr ] = Math . max ( dp [ i ] , max_length [ curr ] ) ; } let ans = 0 ; ans = Math . max ( ... dp ) return ans ; } let s = " " ; let n = s . length ; let k = 3 ; document . write ( longest_subseq ( n , k , s ) ) ;