Minimize replacements with values up to K to make sum of two given arrays equal | Function to find minimum number of replacements required to make the sum of two arrays equal ; Stores the sum of a [ ] ; Stores the sum of b [ ] ; Calculate sum of the array a [ ] ; Calculate sum of the array b [ ] ; Stores the difference between a [ ] and b [ ] ; Left and Right pointer to traverse the array a [ ] ; Left and Right pointer to traverse the array b [ ] ; Stores the count of moves ; Sort the arrays in ascending order ; Iterate while diff != 0 and l1 <= r1 or l2 <= r2 ; If diff is greater than 0 ; If all pointers are valid ; Otherwise , if only pointers of array a [ ] is valid ; Otherwise ; If diff is less than 0 ; If all pointers are valid ; Otherwise , if only pointers of array a [ ] is valid ; Otherwise ; Increment count of res by one ; If diff is 0 , then return res ; Otherwise , return - 1 ; Driver Code
function makeSumEqual ( a , b , K , M , N ) { let sum1 = 0 ; let sum2 = 0 ; for ( let el = 0 ; el < a . length ; el ++ ) sum1 += a [ el ] ; for ( let el = 0 ; el < b . length ; el ++ ) sum2 += b [ el ] ; let diff = sum1 - sum2 ; let l1 = 0 , r1 = M - 1 ; let l2 = 0 , r2 = N - 1 ; let res = 0 ; a . sort ( function ( c , d ) { return c - d ; } ) ; b . sort ( function ( c , d ) { return c - d ; } ) ; while ( l1 <= r1 l2 <= r2 ) { if ( diff == 0 ) { break ; } if ( diff > 0 ) { if ( l2 <= r2 && l1 <= r1 ) { if ( K - b [ l2 ] < a [ r1 ] - 1 ) { let sub = Math . min ( a [ r1 ] - 1 , diff ) ; diff -= sub ; a [ r1 ] -= sub ; r1 -- ; } else { let sub = Math . min ( K - b [ l2 ] , diff ) ; diff -= sub ; b [ l2 ] += sub ; l2 ++ ; } } else if ( l1 <= r1 ) { let sub = Math . min ( a [ r1 ] - 1 , diff ) ; diff -= sub ; a [ r1 ] -= sub ; r1 -- ; } else { let sub = Math . min ( K - b [ l2 ] , diff ) ; diff -= sub ; b [ l2 ] += sub ; l2 ++ ; } } else { if ( l1 <= r1 && l2 <= r2 ) { if ( K - a [ l1 ] < b [ r2 ] - 1 ) { let sub = Math . min ( b [ r2 ] - 1 , - 1 * diff ) ; diff += sub ; b [ r2 ] -= sub ; r2 -- ; } else { let sub = Math . min ( K - a [ l1 ] , - 1 * diff ) ; diff += sub ; a [ l1 ] -= sub ; l1 ++ ; } } else if ( l2 <= r2 ) { let sub = Math . min ( b [ r2 ] - 1 , - 1 * diff ) ; diff += sub ; b [ r2 ] -= sub ; r2 -- ; } else { let sub = Math . min ( K - a [ l1 ] , diff ) ; diff += sub ; a [ l1 ] += sub ; l1 ++ ; } } res ++ ; } if ( diff == 0 ) return res ; else return - 1 ; } let A = [ 1 , 4 , 3 ] ; let B = [ 6 , 6 , 6 ] ; let M = A . length ; let N = B . length ; let K = 6 ; document . write ( makeSumEqual ( A , B , K , M , N ) ) ;