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
function minKBitFlips ( A , K ) { let flip = [ ] ; let count = 0 ; for ( let i = 0 ; i < A . length ; i ++ ) { if ( flip . length != 0 && ( i - flip [ 0 ] >= K ) ) { flip . shift ( ) ; } if ( A [ i ] % 2 == flip . length % 2 ) { if ( i + K - 1 >= A . length ) { return - 1 ; } count ++ ; } } return count ; } let A = [ 0 , 1 , 0 ] ; let K = 1 ; let ans = minKBitFlips ( A , K ) ; document . write ( ans ) ;