Minimum swaps of same | C ++ program for the above approach ; Function to count the minimum swaps of same - indexed elements from arrays arr1 [ ] and arr2 [ ] required to make the sum of both the arrays even ; Store the sum of elements of the array arr1 and arr2 respectively ; Store the array sum of both the arrays ; If both sumArr1 and sumArr2 are even , print 0 and return ; If both sumArr1 and sumArr2 are odd and check for a pair with sum odd sum ; Stores if a pair with odd sum exists or not ; Traverse the array ; If a pair exists with odd sum , set flag = 1 ; Print the answer and return ; For all other cases , print - 1 ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumSwaps ( int arr1 [ ] , int arr2 [ ] , int n ) { int sumArr1 = 0 , sumArr2 = 0 ; for ( int i = 0 ; i < n ; ++ i ) { sumArr1 += arr1 [ i ] ; sumArr2 += arr2 [ i ] ; } if ( sumArr1 % 2 == 0 && sumArr2 % 2 == 0 ) { cout << 0 ; return ; } if ( sumArr1 % 2 != 0 && sumArr2 % 2 != 0 ) { int flag = -1 ; for ( int i = 0 ; i < n ; ++ i ) { if ( ( arr1 [ i ] + arr2 [ i ] ) % 2 == 1 ) { flag = 1 ; break ; } } cout << flag ; return ; } cout << -1 ; } int main ( ) { int arr1 [ ] = { 11 , 14 , 20 , 2 } ; int arr2 [ ] = { 5 , 9 , 6 , 3 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; minimumSwaps ( arr1 , arr2 , N ) ; return 0 ; }