Minimum Subarray flips required to convert all elements of a Binary Array to K | C ++ 14 Program to implement the above approach ; Function to count the minimum number of subarray flips required ; Iterate the array ; If arr [ i ] and flag are equal ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSteps ( int arr [ ] , int n , int k ) { int i , cnt = 0 ; int flag ; if ( k == 1 ) flag = 0 ; else flag = 1 ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == flag ) { cnt ++ ; flag = ( flag + 1 ) % 2 ; } } return cnt ; } int main ( ) { int arr [ ] = { 1 , 0 , 1 , 0 , 0 , 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 1 ; cout << minSteps ( arr , n , k ) ; return 0 ; }