Maximize count of distinct strings generated by replacing similar adjacent digits having sum K with K | Function to find the desired number of strings ; Store the count of strings ; Store the length of the string ; Initialize variable to indicate the start of the substring ;  ; Traverse the string ; If sum of adjacent characters is K mark the starting index and set flag to 1 ; If sum of adjacent characters is not K and the flag variable is set , end the substring here ; Set flag to 0 denoting the end of substring ; Check if the length of the substring formed is odd ; Update the answer ; If flag is set and end of string is reached , mark the end of substring ; Update the answer ; Print the answer ; Driver Code ; Function Call
def countStrings ( s , k ) : NEW_LINE INDENT ans = 1 NEW_LINE lenn = len ( s ) NEW_LINE flag = 0 NEW_LINE DEDENT / * Store the starting index of NEW_LINE INDENT the substring * / NEW_LINE for i in range ( lenn - 1 ) : NEW_LINE INDENT if ( ord ( s [ i ] ) - ord ( '0' ) + ord ( s [ i + 1 ] ) - ord ( '0' ) == k and flag == 0 ) : NEW_LINE INDENT flag = 1 NEW_LINE start_ind = i NEW_LINE DEDENT if ( flag == 1 and ord ( s [ i ] ) - ord ( '0' ) + ord ( s [ i + 1 ] ) - ord ( '0' ) != k ) : NEW_LINE INDENT flag = 0 NEW_LINE if ( ( i - start_ind + 1 ) % 2 != 0 ) : NEW_LINE INDENT ans *= ( i - start_ind + 1 - 1 ) // 2 + 1 NEW_LINE DEDENT DEDENT DEDENT if ( flag == 1 and ( lenn - start_ind ) % 2 != 0 ) : NEW_LINE INDENT ans *= ( lenn - start_ind ) // 2 + 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT S = "313" NEW_LINE K = 4 NEW_LINE countStrings ( S , K ) NEW_LINE