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 ; Store the starting index 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
function countStrings ( s , k ) { var ans = 1 ; var len = s . length ; var flag = 0 ; var start_ind ; for ( var i = 0 ; i < len - 1 ; i ++ ) { if ( ( s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) + s [ i + 1 ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) == k && flag == 0 ) { flag = 1 ; start_ind = i ; } if ( flag == 1 && ( s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) + s [ i + 1 ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) != k ) { flag = 0 ; if ( ( i - start_ind + 1 ) % 2 != 0 ) ans *= ( i - start_ind + 1 - 1 ) / 2 + 1 ; } } if ( flag == 1 && ( len - start_ind ) % 2 != 0 ) ans *= parseInt ( ( len - start_ind ) / 2 ) + 1 ; document . write ( ans ) ; } var S = " " ; var K = 4 ; countStrings ( S , K ) ;