Minimum sum of absolute difference of pairs of two arrays

Given two arrays a[] and b[] of equal length n. The task is to pair each element of array a to an element in array b, such that sum S of absolute differences of all the pairs is minimum.

Suppose, two elements a[i] and a[j] (i != j) of a are paired with elements b[p] and b[q] of b respectively,
then p should not be equal to q.

Examples:



Input :  a[] = {3, 2, 1}
         b[] = {2, 1, 3}
Output : 0

Input :  n = 4
         a[] = {4, 1, 8, 7}
         b[] = {2, 3, 6, 5}
Output : 6

The solution to the problem is a simple greedy approach. It consists of two steps.
Step 1 : Sort both the arrays in O (n log n) time.
Step 2 : Find absolute difference of each pair of corresponding elements (elements at same index) of both arrays and add the result to the sum S. The time complexity of this step is O(n).

Hence, the overall time complexity of the program is O(n log n).

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find minimum sum of absolute
// differences of two arrays.
#include <bits/stdc++.h>
using namespace std;
  
// Returns minimum possible pairwise absolute
// difference of two arrays.
long long int findMinSum(int a[], int b[], int n)
{
    // Sort both arrays
    sort(a, a+n);
    sort(b, b+n);
  
    // Find sum of absolute differences
    long long int sum= 0 ;
    for (int i=0; i<n; i++)
        sum = sum + abs(a[i]-b[i]);
  
    return sum;
}
  
// Driver code
int main()
{
    // Both a[] and b[] must be of same size.
    long long int a[] = {4, 1, 8, 7};
    long long int b[] = {2, 3, 6, 5};
    int n = sizeof(a)/sizeof(a[0]);
    printf("%lld\n", findMinSum(a, b, n));
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find minimum sum of
// absolute differences of two arrays.
import java.util.Arrays;
  
class MinSum
{
    // Returns minimum possible pairwise 
    // absolute difference of two arrays.
    static long findMinSum(long a[], long b[], long n)
    {
        // Sort both arrays
        Arrays.sort(a);
        Arrays.sort(b);
       
        // Find sum of absolute differences
        long sum = 0 ;
        for (int i = 0; i < n; i++)
            sum = sum + Math.abs(a[i] - b[i]);
       
        return sum;
    }
       
    // Driver code
    public static void main(String[] args) 
    {
        // Both a[] and b[] must be of same size.
        long a[] = {4, 1, 8, 7};
        long b[] = {2, 3, 6, 5};
        int n = a.length;
        System.out.println(findMinSum(a, b, n));
    }    
}
   
// This code is contributed by Raghav Sharma

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find minimum sum 
# of absolute differences of two arrays.
def findMinSum(a, b, n):
  
    # Sort both arrays
    a.sort()
    b.sort()
  
    # Find sum of absolute differences
    sum = 0
      
    for i in range(n):
        sum = sum + abs(a[i] - b[i])
  
    return sum
  
# Driver program
      
# Both a[] and b[] must be of same size.
a = [4, 1, 8, 7]
b = [2, 3, 6, 5]
n = len(a)
  
print(findMinSum(a, b, n))
  
# This code is contributed by Anant Agarwal.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find minimum sum of
// absolute differences of two arrays.
using System;
  
class MinSum {
      
    // Returns minimum possible pairwise 
    // absolute difference of two arrays.
    static long findMinSum(long []a, long []b,
                           long n)
    {
          
        // Sort both arrays
        Array.Sort(a);
        Array.Sort(b);
      
        // Find sum of absolute differences
        long sum = 0 ;
        for (int i = 0; i < n; i++)
            sum = sum + Math.Abs(a[i] - b[i]);
      
        return sum;
    }
      
    // Driver code
    public static void Main(String[] args) 
    {
        // Both a[] and b[] must be of same size.
        long []a = {4, 1, 8, 7};
        long []b = {2, 3, 6, 5};
        int n = a.Length;
        Console.Write(findMinSum(a, b, n));
    
}
  
// This code is contributed by parashar...

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find minimum sum 
// of absolute differences of two 
// arrays.
  
// Returns minimum possible pairwise
// absolute difference of two arrays.
function findMinSum($a, $b, $n)
{
      
    // Sort both arrays
    sort($a); 
    sort($a, $n);
    sort($b); 
    sort($b, $n);
  
    // Find sum of absolute 
    // differences
    $sum= 0 ;
    for ($i = 0; $i < $n; $i++)
        $sum = $sum + abs($a[$i] - 
                          $b[$i]);
  
    return $sum;
}
  
    // Driver Code
    // Both a[] and b[] must
    // be of same size.
    $a = array(4, 1, 8, 7);
    $b = array(2, 3, 6, 5);
    $n = sizeof($a);
    echo(findMinSum($a, $b, $n));
  
// This code is contributed by nitin mittal.
?>

chevron_right



Output :

6

This article is contributed by Sahil Bajaj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : parashar, nitin mittal



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.