Minimum inversions required so that no two adjacent elements are same | C ++ implementation of the approach ; Function to return the minimum inversions required so that no two adjacent elements are same ; To store the inversions required to make the array { 1 , 0 , 1 , 0 , 1 , 0 , 1 , ... } and { 0 , 1 , 0 , 1 , 0 , 1 , 0 , ... } respectively ; Find all the changes required ; Return the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_changes ( int a [ ] , int n ) { int ans_a = 0 , ans_b = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { if ( a [ i ] == 0 ) ans_a ++ ; else ans_b ++ ; } else { if ( a [ i ] == 0 ) ans_b ++ ; else ans_a ++ ; } } return min ( ans_a , ans_b ) ; } int main ( ) { int a [ ] = { 1 , 0 , 0 , 1 , 0 , 0 , 1 , 0 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << min_changes ( a , n ) ; return 0 ; }