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
def longest_subseq ( n , k , s ) : NEW_LINE INDENT dp = [ 0 ] * n NEW_LINE max_length = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE lower = max ( 0 , curr - k ) NEW_LINE upper = min ( 25 , curr + k ) NEW_LINE for j in range ( lower , upper + 1 ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , max_length [ j ] + 1 ) NEW_LINE DEDENT max_length [ curr ] = max ( dp [ i ] , max_length [ curr ] ) NEW_LINE DEDENT return max ( dp ) NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE n = len ( s ) NEW_LINE k = 3 NEW_LINE print ( longest_subseq ( n , k , s ) ) NEW_LINE DEDENT main ( ) NEW_LINE