Minimize flips on K |  ; store previous flip events ; remove an item which is out range of window . ; In a window , if A [ i ] is a even number with even times fliped , it need to be fliped again . On other hand , if A [ i ] is a odd number with odd times fliped , it need to be fliped again . ; flip . push ( i ) ; insert ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minKBitFlips ( int A [ ] , int K , int N ) { queue < int > flip ; int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( flip . size ( ) > 0 && ( i - flip . front ( ) >= K ) ) { flip . pop ( ) ; } if ( A [ i ] % 2 == flip . size ( ) % 2 ) { if ( i + K - 1 >= N ) { return -1 ; } count ++ ; } } return count ; } int main ( ) { int A [ ] = { 0 , 1 , 0 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int K = 1 ; int ans = minKBitFlips ( A , K , 3 ) ; cout << ans ; return 0 ; }