Minimize swaps between two arrays such that sum of the first array exceeds sum of the second array | Java 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
import java . io . * ; import java . util . * ; class GFG { static 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 ; } Arrays . sort ( arr1 ) ; Arrays . sort ( arr2 ) ; 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 ; } public static void main ( String [ ] args ) { int [ ] arr1 = new int [ ] { 1 , 3 , 2 , 4 } ; int [ ] arr2 = new int [ ] { 6 , 7 , 8 } ; int N = arr1 . length ; int M = arr2 . length ; System . out . println ( maximumCount ( arr1 , arr2 , N , M ) ) ; } }