You are given an array of n integer and an integer K. Find the number of total unordered pairs {i, j} such that absolute value of |ai + aj – k| is minimal possible where i != j.
If arr[ ] = {0, 4, 6, 2, 4} and k = 7 then we can create following 5 pairs with minimal value as 1
{0, 6}, {4, 2}, {4, 4}, {6, 2}, {2, 4}
Iterate over all possible pairs and for each pair we will check whether the value of (ai + aj – K) is smaller than our current smallest value of not. So as per result of above condition we have total of three cases −
#include <iostream> #include <climits> #include <cmath> using namespace std; void getPairs(int *arr, int n, int k) { int minValue = INT_MAX; int pairs = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { int val = abs(arr[i] + arr[j] - k); if (val < minValue) { minValue = val; pairs = 1; } else if (val == minValue) { ++pairs; } } } cout << "Min value = " << minValue << endl; cout << "Total pairs = " << pairs << endl; } int main() { int arr[] = {0, 4, 6, 2, 4}; int k = 7; int n = sizeof(arr) / sizeof(arr[0]); getPairs(arr, n, k); return 0; }
When you compile and execute above program. It generates following output −
Min value= 1 Total pairs = 5