Maximum number of consecutive 1 s after flipping all 0 s in a K length subarray | Java program for the above approach ; Function to find the maximum number of consecutive 1 's after flipping all zero in a K length subarray ; Initialize variable ; Iterate unil n - k + 1 as we have to go till i + k ; Iterate in the array in left direction till you get 1 else break ; Iterate in the array in right direction till you get 1 else break ; Compute the maximum length ; Return the length ; Driver code ; Array initialization ; Size of array
import java . util . * ; class GFG { static int findmax ( int arr [ ] , int n , int k ) { int trav , i ; int c = 0 , maximum = 0 ; for ( i = 0 ; i < n - k + 1 ; i ++ ) { trav = i - 1 ; c = 0 ; while ( trav >= 0 && arr [ trav ] == 1 ) { trav -- ; c ++ ; } trav = i + k ; while ( trav < n && arr [ trav ] == 1 ) { trav ++ ; c ++ ; } c += k ; if ( c > maximum ) maximum = c ; } return maximum ; } public static void main ( String args [ ] ) { int k = 3 ; int arr [ ] = { 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 } ; int n = arr . length ; int ans = findmax ( arr , n , k ) ; System . out . println ( ans ) ; } }