Making elements of two arrays same with minimum increment / decrement | Javascript program to find minimum increment / decrement operations to make array elements same . ; sorting both arrays in ascending order ; variable to store the final result ; After sorting both arrays Now each array is in non - decreasing order . Thus , we will now compare each element of the array and do the increment or decrement operation depending upon the value of array b [ ] . ; Driver code
function MinOperation ( a , b , n ) { a . sort ( function ( a , b ) { return a - b } ) ; b . sort ( function ( a , b ) { return a - b } ) ; let result = 0 ; for ( let i = 0 ; i < n ; ++ i ) { if ( a [ i ] > b [ i ] ) result = result + Math . abs ( a [ i ] - b [ i ] ) ; else if ( a [ i ] < b [ i ] ) result = result + Math . abs ( a [ i ] - b [ i ] ) ; } return result ; } let a = [ 3 , 1 , 1 ] ; let b = [ 1 , 2 , 2 ] ; let n = a . length ; document . write ( MinOperation ( a , b , n ) ) ;