Minimum possible sum of absolute difference of pairs from given arrays
Last Updated :
03 Apr, 2023
Given two arrays a[] and b[] of size N and M respectively (N < M), the task is to find the minimum possible sum of absolute difference of pairs formed by pairing each element of array a[] with an element of array b[]
Note: Each element of each array can be considered only once.
Examples:
Input: a[] = {2, 3, 5}, b[] = {1, 2, 3, 4, 5}
Output: 0
Explanation: Elements {2, 3, 5} in array a[] can be paired with {2, 3, 5} in array b[].
This will give a minimum absolute difference of 0.
Input: a[] = {1, 4, 5, 8}, b[] = {1, 3, 4, 6, 7}
Output: 2
Naive approach: The easiest way is to sort the arrays and try all the possible combinations to choose N elements from b[] and make pairs with a[].
Time Complexity: O(N*logN + M*logM + MCN)
Auxiliary Space: O(1)
Efficient Approach: This problem can be efficiently solved by using the concept of dynamic programming using the following idea.
For each element at ith position of array a[], the jth element of b[] can either be used to form a pair with a[i] or not.
So the overlapping subproblem property can be used to form a dp[][] array to store the minimum absolute difference till ith element of b[] and jth element of a[] is considered and can be reused for further calculations.
Follow the steps mentioned below to implement the above idea:
- First sort both arrays.
- Initialize a matrix dp[][] where dp[i][j] indicates the total minimum absolute difference till the index ith index of b[] and jth index of a[].
- While iterating through the index of the larger array b[], at each point of iterations there can be two cases:
- Not taking the ith index into consideration of forming pair with minimum absolute difference sum. Then dp[i+1][j] = dp[i][j] as ith index is not considered and are moving to (i+1)th index directly.
- Considering the ith index. So add the absolute difference between elements at both ith and jth index and then move to (i+1)th and (j+1)th index respectively. So total value is dp[i+1][j+1] = dp[i][j] + abs(a[j] - b[i]).
- The value at dp[M][N] is the required answer.
Below is the implementation of the above approach.
C++
// C++ code to implement above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the
// minimum absolute difference
int min_sum(int a[], int b[], int N, int M)
{
// Sorting both the arrays
sort(a, a + N);
sort(b, b + M);
int dp[M + 1][N + 1];
// Initialising the dp to high value
for (int i = 0; i <= M; i++) {
for (int j = 0; j <= N; j++) {
dp[i][j] = 1e9;
}
}
dp[0][0] = 0;
// Iterating through each element
// of the larger array b
for (int i = 0; i < M; i++) {
// Case 1. Where we are not taking
// the element at ith index
for (int j = 0; j <= N; j++) {
dp[i + 1][j] = dp[i][j];
}
// Case 2. When we have to take the
// element at ith index
for (int j = 0; j < N; j++) {
dp[i + 1][j + 1]
= min(dp[i + 1][j + 1],
dp[i][j]
+ abs(a[j] - b[i]));
}
}
return dp[M][N];
}
// Driver code
int main()
{
int a[] = { 1, 4, 5, 8 };
int N = sizeof(a) / sizeof(a[0]);
int b[] = { 1, 3, 4, 6, 7 };
int M = sizeof(b) / sizeof(b[0]);
// Function call
cout << min_sum(a, b, N, M);
return 0;
}
Java
// Java program to implement above approach
import java.util.*;
class GFG {
// Function to return the
// minimum absolute difference
static int min_sum(int[] a, int[] b, int N, int M)
{
// Sorting both the arrays
Arrays.sort(a);
Arrays.sort(b);
int[][] dp = new int[M + 1][N + 1];
// Initialising the dp to high value
for (int i = 0; i <= M; i++) {
for (int j = 0; j <= N; j++) {
dp[i][j] = 1000000000;
}
}
dp[0][0] = 0;
// Iterating through each element
// of the larger array b
for (int i = 0; i < M; i++) {
// Case 1. Where we are not taking
// the element at ith index
for (int j = 0; j <= N; j++) {
dp[i + 1][j] = dp[i][j];
}
// Case 2. When we have to take the
// element at ith index
for (int j = 0; j < N; j++) {
dp[i + 1][ j + 1]
= Math.min(dp[i + 1][j + 1],
dp[i][j]
+ Math.abs(a[j] - b[i]));
}
}
return dp[M][N];
}
// Driver Code
public static void main(String args[])
{
int[] a = { 1, 4, 5, 8 };
int N = a.length;
int[] b = { 1, 3, 4, 6, 7 };
int M = b.length;
// Function call
System.out.print(min_sum(a, b, N, M));
}
}
// This code is contributed by code_hunt.
Python3
# python3 code to implement above approach
# Function to return the
# minimum absolute difference
def min_sum(a, b, N, M):
# Sorting both the arrays
a.sort()
b.sort()
dp = [[0 for _ in range(N+1)] for _ in range(M+1)]
# Initialising the dp to high value
for i in range(0, M + 1):
for j in range(0, N+1):
dp[i][j] = int(1e9)
dp[0][0] = 0
# Iterating through each element
# of the larger array b
for i in range(0, M):
# Case 1. Where we are not taking
# the element at ith index
for j in range(0, N+1):
dp[i + 1][j] = dp[i][j]
# Case 2. When we have to take the
# element at ith index
for j in range(0, N):
dp[i + 1][j + 1] = min(dp[i + 1][j + 1],
dp[i][j]
+ abs(a[j] - b[i]))
return dp[M][N]
# Driver code
if __name__ == "__main__":
a = [1, 4, 5, 8]
N = len(a)
b = [1, 3, 4, 6, 7]
M = len(b)
# Function call
print(min_sum(a, b, N, M))
# This code is contributed by rakeshsahni
C#
// C# code to implement above approach
using System;
public class GFG{
// Function to return the
// minimum absolute difference
static int min_sum(int[] a, int[] b, int N, int M)
{
// Sorting both the arrays
Array.Sort(a);
Array.Sort(b);
int[,] dp = new int[M + 1, N + 1];
// Initialising the dp to high value
for (int i = 0; i <= M; i++) {
for (int j = 0; j <= N; j++) {
dp[i,j] = 1000000000;
}
}
dp[0,0] = 0;
// Iterating through each element
// of the larger array b
for (int i = 0; i < M; i++) {
// Case 1. Where we are not taking
// the element at ith index
for (int j = 0; j <= N; j++) {
dp[i + 1, j] = dp[i, j];
}
// Case 2. When we have to take the
// element at ith index
for (int j = 0; j < N; j++) {
dp[i + 1, j + 1]
= Math.Min(dp[i + 1, j + 1],
dp[i, j]
+ Math.Abs(a[j] - b[i]));
}
}
return dp[M, N];
}
// Driver code
static public void Main (){
int[] a = { 1, 4, 5, 8 };
int N = a.Length;
int[] b = { 1, 3, 4, 6, 7 };
int M = b.Length;
// Function call
Console.Write(min_sum(a, b, N, M));
}
}
// This code is contributed by hrithikgarg03188.
JavaScript
<script>
// JavaScript code for the above approach
// Function to return the
// minimum absolute difference
function min_sum(a,b,N, M)
{
// Sorting both the arrays
a.sort();
b.sort();
let dp = new Array(M+1);
for(let i=0;i<dp.length;i++) {
dp[i] = new Array(N+1)
}
// Initialising the dp to high value
for (let i = 0; i <= M; i++) {
for (let j = 0; j <= N; j++) {
dp[i][j] = 1e9;
}
}
dp[0][0] = 0;
// Iterating through each element
// of the larger array b
for (let i = 0; i < M; i++) {
// Case 1. Where we are not taking
// the element at ith index
for (let j = 0; j <= N; j++) {
dp[i + 1][j] = dp[i][j];
}
// Case 2. When we have to take the
// element at ith index
for (let j = 0; j < N; j++) {
dp[i + 1][j + 1]
= Math.min(dp[i + 1][j + 1],
dp[i][j]
+ Math.abs(a[j] - b[i]));
}
}
return dp[M][N];
}
// Driver code
let a = [1, 4, 5, 8];
let N = a.length;
let b = [1, 3, 4, 6, 7 ];
let M = b.length;
// Function call
document.write(min_sum(a, b, N, M));
// This code is contributed by Potta Lokesh
</script>
Time complexity: O(N * M log N)
Auxiliary Space: O(N * M)
Similar Reads
Minimum sum of absolute differences of pairs in a triplet from three arrays Given three arrays a[], b[] and c[] of sizes A, B and C respectively, the task is to find the minimum possible value of abs(a[i] - b[j]) + abs(b[j] - c[k]) where 0 ? i ? A, 0 ? j ? B and 0 ? k ? C. Examples: Input: A = 3, B = 2, C = 2, a[] = {1, 8, 5}, b[] = {2, 9}, c[] = {5, 4}Output: 3Explanation:
11 min read
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
7 min read
Sum of absolute differences of all pairs in a given array Given a sorted array of distinct elements, the task is to find the summation of absolute differences of all pairs in the given array. Examples: Input : arr[] = {1, 2, 3, 4} Output: 10 Sum of |2-1| + |3-1| + |4-1| + |3-2| + |4-2| + |4-3| = 10 Input : arr[] = {1, 8, 9, 15, 16} Output: 74 Input : arr[]
11 min read
Minimum and Maximum sum of absolute differences of pairs Given an array of N integers where N is even, find the minimum and maximum sum of absolute difference of N/2 pairs formed by pairing every element with one other element. Examples: Input: a[] = {10, -10, 20, -40} Output: min_sum = 40, max_sum = 80 Explanation: Pairs selected for minimum sum (-10, -4
8 min read
Minimum sum of absolute differences between pairs of a triplet from an array Given an array A[] consisting of positive integers, the task is to find the minimum value of |A[x] - A[y]| + |A[y] - A[z]| of any triplet (A[x], A[y], A[z]) from an array. Examples: Input: A[] = { 1, 1, 2, 3 }Output: 1Explanation:For x = 0, y = 1, z = 2|A[x] - A[y]| + |A[y] - A[z]| = 0 + 1 = 1, whic
5 min read
Sum of minimum absolute differences in an array Given an array of n distinct integers. The task is to find the sum of minimum absolute difference of each array element. For an element arr[i] present at index i in the array, its minimum absolute difference is calculated as: Min absolute difference (arr[i]) = min(abs(arr[i] - arr[j])), where 0 <
7 min read