Rearrange two given arrays to maximize sum of same indexed elements
Last Updated :
18 May, 2021
Given two arrays A[] and B[] of size N, the task is to find the maximum possible sum of abs(A[i] – B[i]) by rearranging the array elements.
Examples:
Input: A[] = {1, 2, 3, 4, 5}, B[] = {1, 2, 3, 4, 5}
Output: 12
Explanation:
One of the possible rearrangements of A[] is {5, 4, 3, 2, 1}.
One of the possible rearrangements of B[] is {1, 2, 3, 4, 4}.
Therefore, the sum of all possible values of abs(A[i] – B[i]) = { abs(5 – 1) + abs(4 – 2) + abs(3 – 3) + abs(2 – 4) + abs(1 – 5) } = 12
Input: A[] = {1, 2, 2, 4, 5}, B[] = {5, 5, 5, 6, 6}
Output: 13
Explanation:
One of the possible rearrangements of A[] is {5, 4, 2, 2, 1}.
One of the possible rearrangements of B[] is {5, 5, 5, 6, 6}.
Therefore, the sum of all possible values of abs(A[i] – B[i]) = { abs(5 – 5) + abs(4 – 5) + abs(2 – 5) + abs(2 – 6) + abs(1 – 6) } = 13
Approach: Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
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;
}
|
Java
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));
}
}
|
Python3
def MaxRearrngeSum(A, B, N):
A.sort()
B.sort(reverse = True )
maxSum = 0
for i in range (N):
maxSum + = abs (A[i] - B[i])
return maxSum
if __name__ = = "__main__" :
A = [ 1 , 2 , 2 , 4 , 5 ]
B = [ 5 , 5 , 5 , 6 , 6 ]
N = len (A)
print (MaxRearrngeSum(A, B, N))
|
C#
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));
}
}
|
Javascript
<script>
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));
</script>
|
Time Complexity: O(N * Log N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...