Minimize swaps between two arrays such that sum of the first array exceeds sum of the second array | 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
function maximumCount ( arr1 , arr2 , s1 , s2 ) { let sum1 = 0 , sum2 = 0 ; for ( let i = 0 ; i < s1 ; i ++ ) { sum1 += arr1 [ i ] ; } for ( let j = 0 ; j < s2 ; j ++ ) { sum2 += arr2 [ j ] ; } let len = 0 ; if ( s1 >= s2 ) { len = s2 ; } else { len = s1 ; } arr1 . sort ( ) ; arr2 . sort ( ) ; let j = 0 , k = s2 - 1 , count = 0 ; for ( let i = 0 ; i < len ; i ++ ) { if ( sum1 <= sum2 ) { if ( arr2 [ k ] >= arr1 [ i ] ) { let dif1 = arr1 [ j ] , dif2 = arr2 [ k ] ; sum1 -= dif1 ; sum1 += dif2 ; sum2 -= dif2 ; sum2 += dif1 ; j ++ ; k -- ; count ++ ; } else { break ; } } else { break ; } } return count ; } let arr1 = [ 1 , 3 , 2 , 4 ] ; let arr2 = [ 6 , 7 , 8 ] ; let N = arr1 . length ; let M = arr2 . length ; document . write ( maximumCount ( arr1 , arr2 , N , M ) ) ;