Minimize flips on K | Java program for the above approach ; Function to find the minimum number K - length subarrays required to be flipped to make all array elements 1 ; Stores whether an element can be flipped or not ; Store the required number of flips ; Traverse the array , A [ ] ; Find the prefix sum for the indices i > 0 ; Check if the current element is required to be flipped ; If subarray of size K is not possible , then print - 1 and return ; Increment ans by 1 ; Change the current state of the element ; Decrement isFlipped [ i + K ] ; If subarray of size K is not possible , then print - 1 and return ; Increment ans by 1 ; Change the current state of the element ; Decrement isFlipped [ i + K ] ; Print the result ; Driver Code
class GFG { static void minimumOperations ( int [ ] A , int K ) { int [ ] isflipped = new int [ A . length + 1 ] ; int ans = 0 ; for ( int i = 0 ; i < A . length ; i ++ ) { if ( i > 0 ) { isflipped [ i ] += isflipped [ i - 1 ] ; isflipped [ i ] %= 2 ; } if ( A [ i ] == 0 && isflipped [ i ] == 0 ) { if ( ( A . length - i + 1 ) <= K ) { System . out . println ( - 1 ) ; return ; } ans ++ ; isflipped [ i ] ++ ; isflipped [ i + K ] -- ; } else if ( A [ i ] == 1 && isflipped [ i ] != 0 ) { if ( ( A . length - i + 1 ) <= K ) { System . out . println ( - 1 ) ; return ; } ans ++ ; isflipped [ i ] ++ ; isflipped [ i + K ] -- ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 0 , 1 , 0 } ; int K = 1 ; minimumOperations ( arr , K ) ; } }