Given two arrays a and b of equal length, pair each element of array a to an element in array b, such that the sum of the absolute differences of all the pairs is minimum
Examples:
Input: a = [4, 1, 2], b = [2, 4, 1]
Output: 0
Explanation: If we take the pairings as (4,4), (1,1), and (2,2),
the sum will be S = |4 - 4| + |1 - 1| +|2 - 2| = 0.
It can be shown that this is the minimum sum we can get.
Input: a = [4, 1, 8, 7], b = [2, 3, 6, 5]
Output: 6
Explanation:If we take the pairings as (1,2), (4,3), (7,5), and (8,6),
the sum will be S = |1 - 2| + |4 - 3| + |7 - 5| + |8 - 6| = 6.
It can be shown that this is the minimum sum we can get.
Table of Content
[Naive Approach] Try All Permutations - O(n*n!) Time O(n) Space
Try all permutations of b[] to be mapped with a[]. We first pair an element of b[] with a[], recursively call for the remaining array and then backtrack to remove the pairing.
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
// Generate all possible pairings
int solve(vector<int> &a, vector<int> &b,
vector<bool> &used,
int idx)
{
int n = a.size();
// All elements paired
if (idx == n)
return 0;
int res = INT_MAX;
// Try pairing a[idx] with every unused b[j]
for (int j = 0; j < n; j++)
{
if (!used[j])
{
used[j] = true;
int curr = abs(a[idx] - b[j]) +
solve(a, b, used, idx + 1);
res = min(res, curr);
used[j] = false;
}
}
return res;
}
int findMinSum(vector<int> &a, vector<int> &b)
{
int n = a.size();
// To track used elements in b
vector<bool> used(n, false);
return solve(a, b, used, 0);
}
int main()
{
vector<int> a = {4, 1, 8, 7};
vector<int> b = {2, 3, 6, 5};
cout << findMinSum(a, b);
return 0;
}
#include <stdio.h>
#include <limits.h>
// Generate all possible pairings
int solve(int a[], int b[], int used[], int idx, int n) {
// All elements paired
if (idx == n)
return 0;
int res = INT_MAX;
// Try pairing a[idx] with every unused b[j]
for (int j = 0; j < n; j++) {
if (!used[j]) {
used[j] = 1;
int curr = abs(a[idx] - b[j]) +
solve(a, b, used, idx + 1, n);
res = res < curr? res : curr;
used[j] = 0;
}
}
return res;
}
int findMinSum(int a[], int b[], int n) {
int used[n];
for (int i = 0; i < n; i++)
used[i] = 0;
return solve(a, b, used, 0, n);
}
int main() {
int a[] = {4, 1, 8, 7};
int b[] = {2, 3, 6, 5};
int n = sizeof(a) / sizeof(a[0]);
printf("%d", findMinSum(a, b, n));
return 0;
}
import java.util.Arrays;
public class Main {
// Generate all possible pairings
static int solve(int