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
import java . lang . Math ; import java . util . Arrays ; import java . util . Collections ; class GFG { static int MaxRearrngeSum ( Integer A [ ] , Integer B [ ] , int N ) { Arrays . sort ( A ) ; Arrays . sort ( B , Collections . reverseOrder ( ) ) ; int maxSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { maxSum += Math . abs ( A [ i ] - B [ i ] ) ; } return maxSum ; } public static void main ( String [ ] args ) { Integer A [ ] = { 1 , 2 , 2 , 4 , 5 } ; Integer B [ ] = { 5 , 5 , 5 , 6 , 6 } ; int N = A . length ; System . out . println ( MaxRearrngeSum ( A , B , N ) ) ; } }