Maximum length substring having all same characters after k changes | C ++ program to find maximum length equal character string with k changes ; function to find the maximum length of substring having character ch ; traverse the whole string ; if character is not same as ch increase count ; While count > k traverse the string again until count becomes less than k and decrease the count when characters are not same ; length of substring will be rightIndex - leftIndex + 1. Compare this with the maximum length and return maximum length ; function which returns maximum length of substring ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findLen ( string & A , int n , int k , char ch ) { int maxlen = 1 ; int cnt = 0 ; int l = 0 , r = 0 ; while ( r < n ) { if ( A [ r ] != ch ) ++ cnt ; while ( cnt > k ) { if ( A [ l ] != ch ) -- cnt ; ++ l ; } maxlen = max ( maxlen , r - l + 1 ) ; ++ r ; } return maxlen ; } int answer ( string & A , int n , int k ) { int maxlen = 1 ; for ( int i = 0 ; i < 26 ; ++ i ) { maxlen = max ( maxlen , findLen ( A , n , k , i + ' A ' ) ) ; maxlen = max ( maxlen , findLen ( A , n , k , i + ' a ' ) ) ; } return maxlen ; } int main ( ) { int n = 5 , k = 2 ; string A = " ABABA " ; cout << " Maximum ▁ length ▁ = ▁ " << answer ( A , n , k ) << endl ; n = 6 , k = 4 ; string B = " HHHHHH " ; cout << " Maximum ▁ length ▁ = ▁ " << answer ( B , n , k ) << endl ; return 0 ; }