Maximum length of consecutive 1 s or 0 s after flipping at most K characters | Java program for the above approach ; Function to find the maximum length continuos segment of character c after flipping at most K characters ; Stores the maximum length ; Stores the count of char ' c ' ; Start of window ; Remove the extra ' c ' from left ; Increment the value of the left ; Update the resultant maximum length of character ch ; Function to find the maximum length of consecutive 0 s or 1 s by flipping at most K characters of the string ; Print the maximum of the maximum length of 0 s or 1 s ; Driver Code
public class GFG { static int maxLength ( String str , int n , char c , int k ) { int ans = - 1 ; int cnt = 0 ; int left = 0 ; for ( int right = 0 ; right < n ; right ++ ) { if ( str . charAt ( right ) == c ) { cnt ++ ; } while ( cnt > k ) { if ( str . charAt ( left ) == c ) { cnt -- ; } left ++ ; } ans = Math . max ( ans , right - left + 1 ) ; } return ans ; } static int maxConsecutiveSegment ( String S , int K ) { int N = S . length ( ) ; return Math . max ( maxLength ( S , N , '0' , K ) , maxLength ( S , N , '1' , K ) ) ; } int main ( ) { return 0 ; } public static void main ( String [ ] args ) { String S = "1001" ; int K = 1 ; System . out . println ( maxConsecutiveSegment ( S , K ) ) ; } }