Maximize count of distinct strings generated by replacing similar adjacent digits having sum K with K | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countStrings ( string s , int k ) { int ans = 1 ; int len = s . size ( ) ; int flag = 0 ; int start_ind ; for ( int i = 0 ; i < len - 1 ; i ++ ) { if ( s [ i ] - '0' + s [ i + 1 ] - '0' == k && flag == 0 ) { flag = 1 ; start_ind = i ; } if ( flag == 1 && s [ i ] - '0' + s [ i + 1 ] - '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 *= ( len - start_ind ) / 2 + 1 ; cout << ans ; } int main ( ) { string S = "313" ; int K = 4 ; countStrings ( S , K ) ; }