Longest subsequence having difference atmost K | Java program for the above approach ; 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
class GFG { static int longest_subseq ( int n , int k , String s ) { int [ ] dp = new int [ n ] ; int [ ] max_length = new int [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { int curr = s . charAt ( i ) - ' a ' ; int lower = Math . max ( 0 , curr - k ) ; int upper = Math . min ( 25 , curr + k ) ; for ( int 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 ] ) ; } int ans = 0 ; for ( int i : dp ) ans = Math . max ( i , ans ) ; return ans ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; int n = s . length ( ) ; int k = 3 ; System . out . print ( longest_subseq ( n , k , s ) ) ; } }