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
def minimumOperations ( A , K ) : NEW_LINE INDENT isflipped = [ 0 ] * ( len ( A ) + 1 ) NEW_LINE ans = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( i > 0 ) : NEW_LINE INDENT isflipped [ i ] += isflipped [ i - 1 ] NEW_LINE isflipped [ i ] %= 2 NEW_LINE DEDENT if ( A [ i ] == 0 and not isflipped [ i ] ) : NEW_LINE INDENT if ( ( len ( A ) - i + 1 ) <= K ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT ans += 1 NEW_LINE isflipped [ i ] += 1 NEW_LINE isflipped [ i + K ] -= 1 NEW_LINE DEDENT elif ( A [ i ] == 1 and isflipped [ i ] ) : NEW_LINE INDENT if ( ( len ( A ) - i + 1 ) <= K ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT ans += 1 NEW_LINE isflipped [ i ] += 1 NEW_LINE isflipped [ i + K ] -= 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , 1 , 0 ] NEW_LINE K = 1 NEW_LINE minimumOperations ( arr , K ) NEW_LINE DEDENT