C++ Program to find out the minimum difference value in n integer pairs



Suppose, we are given two arrays a and b that have a total of n and m values in them respectively. We have to make n or m number of pairs (whichever is minimum) using values from the two arrays. A pair must contain a value from array a and another one from array b. We have to make the pairs in such a way so that the difference of the value in the pairs is minimum and the same. We print the value as output.

So, if the input is like n = 4, m = 4, a = {2, 3, 4, 7}, b = {3, 4, 6, 5}, then the output will be 1.

The pairs that can be made are −

(3, 4), (4, 5), (7, 6), (2, 3).

The difference in the value in all pairs is 1.

Steps

To solve this, we will follow these steps −

sort the array a Define an array s1 initialized with 0 Define an array s2 initialized with 0 for initialize i := 1, when i < n, update i := i + 2, do: insert last element of s1 + a[i] - a[i - 1] at the end of s1 for initialize i := 2, when i < n, update i := i + 2, do: insert last element of s2 + a[i] - a[i - 1] at the end of s2 ans := infinity for each value w in b, do: diff := first element in the array a not less than w - first value of a sub := last element of s1[diff / 2] + s2 ans := minimum of ans and sub print(ans)

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; const int INF = 1e9; void solve(int n, int m, vector<int> a, vector<int> b){    sort(a.begin(), a.end());    vector<int> s1 = {0};    vector<int> s2 = {0};    for (int i = 1; i < n; i += 2)       s1.push_back(a[i] - a[i - 1] + s1.back());    for (int i = 2; i < n; i += 2)       s2.push_back(a[i] - a[i - 1] + s2.back());    int ans = INF;    for (const auto & w : b) {       int diff = lower_bound(a.begin(), a.end(), w) - a.begin();       int sub = s1[diff / 2] + s2.back() - s2[diff / 2] + abs(a[diff / 2 * 2] - w);     ans = min(ans, sub);    } cout << ans << endl; } int main() { int n = 4, m = 4; vector<int> a = {2, 3, 4, 7}, b = {3, 4, 6, 5}; solve(n, m, a, b); return 0; }

Input

4, 4, {2, 3, 4, 7}, {3, 4, 6, 5}

Output

1
Updated on: 2022-03-02T11:09:42+05:30

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements