Rearrange two given arrays to maximize sum of same indexed elements | Java program to implement the above approach ; 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
using System ; class GFG { static int MaxRearrngeSum ( int [ ] A , int [ ] B , int N ) { Array . Sort ( A ) ; Array . Sort ( B ) ; Array . Reverse ( B ) ; int maxSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { maxSum += Math . Abs ( A [ i ] - B [ i ] ) ; } return maxSum ; } public static void Main ( ) { int [ ] A = { 1 , 2 , 2 , 4 , 5 } ; int [ ] B = { 5 , 5 , 5 , 6 , 6 } ; int N = A . Length ; Console . WriteLine ( MaxRearrngeSum ( A , B , N ) ) ; } }