Minimize swaps between two arrays such that sum of the first array exceeds sum of the second array | C ++ program for the above approach ; Function to find the minimum count of swaps required between the two arrays to make the sum of arr1 [ ] greater than that of arr2 [ ] ; Stores the sum of the two arrays ; Calculate sum of arr1 [ ] ; Calculate sum of arr2 [ ] ; Sort the arrays arr1 [ ] and arr2 [ ] ; Traverse the array arr [ ] ; If the sum1 is less than or equal to sum2 ; Swapping the elements ; Update the sum1 and sum2 ; Increment the count ; Return the final count ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumCount ( int arr1 [ ] , int arr2 [ ] , int s1 , int s2 ) { int sum1 = 0 , sum2 = 0 ; for ( int i = 0 ; i < s1 ; i ++ ) { sum1 += arr1 [ i ] ; } for ( int j = 0 ; j < s2 ; j ++ ) { sum2 += arr2 [ j ] ; } int len = 0 ; if ( s1 >= s2 ) { len = s2 ; } else { len = s1 ; } sort ( arr1 , arr1 + s1 ) ; sort ( arr2 , arr2 + s2 ) ; int j = 0 , k = s2 - 1 , count = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( sum1 <= sum2 ) { if ( arr2 [ k ] >= arr1 [ i ] ) { int dif1 = arr1 [ j ] , dif2 = arr2 [ k ] ; sum1 -= dif1 ; sum1 += dif2 ; sum2 -= dif2 ; sum2 += dif1 ; j ++ ; k -- ; count ++ ; } else { break ; } } else { break ; } } return count ; } int main ( ) { int arr1 [ ] = { 1 , 3 , 2 , 4 } ; int arr2 [ ] = { 6 , 7 , 8 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int M = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << maximumCount ( arr1 , arr2 , N , M ) ; return 0 ; }