# Minimum Possible value of |ai + aj – k| for given array and k in C++

C++Server Side ProgrammingProgramming

## Problem statement

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.

## Example

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}

## Algorithm

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 −

• abs( ai + aj – K) > smallest − do nothing as this pair will not count in minimal possible value.
• abs(ai + aj – K) = smallest − increment the count of pair resulting minimal possible value.
• abs( ai + aj – K) < smallest − update the smallest value and set count to 1.

## Example

#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;
}

## Output

When you compile and execute above program. It generates following output −

Min value= 1
Total pairs = 5
Published on 22-Nov-2019 11:07:58