给定两个数组a []和b [] ,它们的长度为n 。任务是将数组a的每个元素与数组b中的元素配对,以使所有对的绝对差之和S最小。
假设,两个元素A [1]和a [j]的(I!= j)的一个与元件B [P]和B B的[Q]分别配对,
那么p不应该等于q 。
例子:
Input : a[] = {3, 2, 1}
b[] = {2, 1, 3}
Output : 0
Explaination :
1st pairing: |3 - 2| + |2 - 1| + |1 - 3|
= 1 + 1 + 2 = 4
2nd pairing: |3 - 2| + |1 - 1| + |2 - 3|
= 1 + 0 + 1 = 2
3rd pairing: |2 - 2| + |3 - 1| + |1 - 3|
= 0 + 2 + 2 = 4
4th pairing: |1 - 2| + |2 - 1| + |3 - 3|
= 1 + 1 + 0 = 2
5th pairing: |2 - 2| + |1 - 1| + |3 - 3|
= 0 + 0 + 0 = 0
6th pairing: |1 - 2| + |3 - 1| + |2 - 3|
= 1 + 2 + 1 = 4
Therefore, 5th pairing has minimum sum of
absolute difference.
Input : n = 4
a[] = {4, 1, 8, 7}
b[] = {2, 3, 6, 5}
Output : 6
解决问题的方法是一种简单的贪婪方法。它包括两个步骤。
步骤1 :以O(n log n)时间对两个数组进行排序。
步骤2 :找到两个数组的每对对应元素(元素在相同索引处)的绝对差,并将结果加到和S上。此步骤的时间复杂度为O(n) 。
因此,该程序的总时间复杂度为O(n log n) 。
C++
// C++ program to find minimum sum of absolute
// differences of two arrays.
#include
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
Java
// 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
Python3
# 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.
C#
// 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...
PHP
Javascript
输出 :
6