Rearrange two given arrays to maximize sum of same indexed elements | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxRearrngeSum ( int A [ ] , int B [ ] , int N ) { sort ( A , A + N ) ; sort ( B , B + N , greater < int > ( ) ) ; int maxSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { maxSum += abs ( A [ i ] - B [ i ] ) ; } return maxSum ; } int main ( ) { int A [ ] = { 1 , 2 , 2 , 4 , 5 } ; int B [ ] = { 5 , 5 , 5 , 6 , 6 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << MaxRearrngeSum ( A , B , N ) ; return 0 ; }