Minimize flips on K | 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
function minimumOperations ( A , K ) { let isflipped = [ ] ; for ( let i = 0 ; i < A . length + 1 ; i ++ ) { isflipped [ i ] = 0 ; } let ans = 0 ; for ( let 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 ) { document . write ( - 1 ) ; return ; } ans ++ ; isflipped [ i ] ++ ; isflipped [ i + K ] -- ; } else if ( A [ i ] == 1 && isflipped [ i ] != 0 ) { if ( ( A . length - i + 1 ) <= K ) { document . write ( - 1 ) ; return ; } ans ++ ; isflipped [ i ] ++ ; isflipped [ i + K ] -- ; } } document . write ( ans ) ; } let arr = [ 0 , 1 , 0 ] ; let K = 1 ; minimumOperations ( arr , K ) ;