Rearrange two given arrays to maximize sum of same indexed elements | Function to find the maximum possible sum by rearranging the given array elements ; Sort the array A [ ] in ascending order ; Sort the array B [ ] in descending order ; Stores maximum possible sum by rearranging array elements ; Traverse both the arrays ; Update maxSum ; Driver Code
function MaxRearrngeSum ( A , B , N ) { A . sort ( ) ; B . sort ( ) ; B . reverse ( ) ; let maxSum = 0 ; for ( let i = 0 ; i < N ; i ++ ) { maxSum += Math . abs ( A [ i ] - B [ i ] ) ; } return maxSum ; } let A = [ 1 , 2 , 2 , 4 , 5 ] ; let B = [ 5 , 5 , 5 , 6 , 6 ] ; let N = A . length ; document . write ( MaxRearrngeSum ( A , B , N ) ) ;