Minimum flips in a Binary array such that XOR of consecutive subarrays of size K have different parity | Function to find the minimum flips required in binary array ; Boolean value to indicate odd or even value of 1 's ; Loop to iterate over the subarrays of size K ; curr_index is used to iterate over all the subarrays ; Loop to iterate over the array at the jump of K to consider every parity ; Condition to check if the subarray is at even position ; The value needs to be same as the first subarray ; The value needs to be opposite of the first subarray ; Update the minimum difference ; Condition to check if the 1 s in the subarray is odd ; Driver Code
function count_flips ( a , n , k ) { var set = false ; var ans = 0 , min_diff = Number . MAX_VALUE ; for ( i = 0 ; i < k ; i ++ ) { var curr_index = i , segment = 0 , count_zero = 0 , count_one = 0 ; while ( curr_index < n ) { if ( segment % 2 == 0 ) { if ( a [ curr_index ] == 1 ) count_zero ++ ; else count_one ++ ; } else { if ( a [ curr_index ] == 0 ) count_zero ++ ; else count_one ++ ; } curr_index = curr_index + k ; segment ++ ; } ans += Math . min ( count_one , count_zero ) ; if ( count_one < count_zero ) set = ! set ; min_diff = Math . min ( min_diff , Math . abs ( count_zero - count_one ) ) ; } if ( set ) return ans ; else return ans + min_diff ; } var n = 6 , k = 3 ; var a = [ 0 , 0 , 1 , 1 , 0 , 0 ] ; document . write ( count_flips ( a , n , k ) ) ;