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), i.e., |ai + aj – k| is minimal possible, where i != j.
Examples:
Input: arr[] = {0, 4, 6, 2, 4}, K = 7
Output: Minimal Value = 1, Total Pairs = 5
Explanation: Pairs resulting minimal value are : {a1, a3}, {a2, a4}, {a2, a5}, {a3, a4}, {a4, a5}
Input: arr[] = {4, 6, 2, 4} , K = 9
Output: Minimal Value = 1, Total Pairs = 4
Explanation: Pairs resulting minimal value are : {a1, a2}, {a1, a4}, {a2, a3}, {a2, a4}
A simple solution is 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.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void pairs( int arr[], int n, int k)
{
int smallest = INT_MAX;
int count = 0;
for ( int i = 0; i < n; i++)
for ( int j = i + 1; j < n; j++) {
if ( abs (arr[i] + arr[j] - k) < smallest) {
smallest = abs (arr[i] + arr[j] - k);
count = 1;
}
else if ( abs (arr[i] + arr[j] - k) == smallest)
count++;
}
cout << "Minimal Value = " << smallest << "\n" ;
cout << "Total Pairs = " << count << "\n" ;
}
int main()
{
int arr[] = { 3, 5, 7, 5, 1, 9, 9 };
int k = 12;
int n = sizeof (arr) / sizeof (arr[0]);
pairs(arr, n, k);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void pairs( int arr[], int n, int k)
{
int smallest = Integer.MAX_VALUE;
int count = 0 ;
for ( int i = 0 ; i < n; i++)
for ( int j = i + 1 ; j < n; j++) {
if (Math.abs(arr[i] + arr[j] - k)
< smallest) {
smallest
= Math.abs(arr[i] + arr[j] - k);
count = 1 ;
}
else if (Math.abs(arr[i] + arr[j] - k)
== smallest)
count++;
}
System.out.println( "Minimal Value = " + smallest);
System.out.println( "Total Pairs = " + count);
}
public static void main(String[] args)
{
int arr[] = { 3 , 5 , 7 , 5 , 1 , 9 , 9 };
int k = 12 ;
int n = arr.length;
pairs(arr, n, k);
}
}
|
Python3
def pairs(arr, n, k):
smallest = 999999999999
count = 0
for i in range (n):
for j in range (i + 1 , n):
if abs (arr[i] + arr[j] - k) < smallest:
smallest = abs (arr[i] + arr[j] - k)
count = 1
elif abs (arr[i] + arr[j] - k) = = smallest:
count + = 1
print ( "Minimal Value = " , smallest)
print ( "Total Pairs = " , count)
if __name__ = = '__main__' :
arr = [ 3 , 5 , 7 , 5 , 1 , 9 , 9 ]
k = 12
n = len (arr)
pairs(arr, n, k)
|
C#
using System;
class GFG {
static void pairs( int [] arr, int n, int k)
{
int smallest = 0;
int count = 0;
for ( int i = 0; i < n; i++)
for ( int j = i + 1; j < n; j++) {
if (Math.Abs(arr[i] + arr[j] - k)
< smallest) {
smallest
= Math.Abs(arr[i] + arr[j] - k);
count = 1;
}
else if (Math.Abs(arr[i] + arr[j] - k)
== smallest)
count++;
}
Console.WriteLine( "Minimal Value = " + smallest);
Console.WriteLine( "Total Pairs = " + count);
}
public static void Main()
{
int [] arr = { 3, 5, 7, 5, 1, 9, 9 };
int k = 12;
int n = arr.Length;
pairs(arr, n, k);
}
}
|
PHP
<?php
function pairs( $arr , $n , $k )
{
$smallest = PHP_INT_MAX;
$count = 0;
for ( $i = 0; $i < $n ; $i ++)
for ( $j = $i + 1; $j < $n ; $j ++)
{
if ( abs ( $arr [ $i ] + $arr [ $j ] - $k ) < $smallest )
{
$smallest = abs ( $arr [ $i ] + $arr [ $j ] - $k );
$count = 1;
}
else if ( abs ( $arr [ $i ] +
$arr [ $j ] - $k ) == $smallest )
$count ++;
}
echo "Minimal Value = " , $smallest , "\n" ;
echo "Total Pairs = " , $count , "\n" ;
}
$arr = array (3, 5, 7, 5, 1, 9, 9);
$k = 12;
$n = sizeof( $arr );
pairs( $arr , $n , $k );
?>
|
Javascript
<script>
function pairs(arr, n, k)
{
var smallest = 1000000000;
var count=0;
for ( var i=0; i<n; i++)
for ( var j=i+1; j<n; j++)
{
if ( Math.abs(arr[i] + arr[j] - k) < smallest )
{
smallest = Math.abs(arr[i] + arr[j] - k);
count = 1;
}
else if (Math.abs(arr[i] + arr[j] - k) == smallest)
count++;
}
document.write( "Minimal Value = " + smallest + "<br>" );
document.write( "Total Pairs = " + count + "<br>" );
}
var arr = [3, 5, 7, 5, 1, 9, 9];
var k = 12;
var n = arr.length;
pairs(arr, n, k);
</script>
|
OutputMinimal Value = 0
Total Pairs = 4
Time Complexity: O(n2) where n is the number of elements in the array.
Auxiliary Space : O(1)
An efficient solution is to use a self balancing binary search tree (which is implemented in set in C++ and TreeSet in Java). We can find closest element in O(log n) time in map.
C++
#include <bits/stdc++.h>
using namespace std;
void pairs( int arr[], int n, int k)
{
int smallest = INT_MAX, count = 0;
set< int > s;
s.insert(arr[0]);
for ( int i = 1; i < n; i++) {
int lower
= *lower_bound(s.begin(), s.end(), k - arr[i]);
int upper
= *upper_bound(s.begin(), s.end(), k - arr[i]);
int curr_min = min( abs (lower + arr[i] - k),
abs (upper + arr[i] - k));
if (curr_min < smallest) {
smallest = curr_min;
count = 1;
}
else if (curr_min == smallest)
count++;
s.insert(arr[i]);
}
cout << "Minimal Value = " << smallest << "\n" ;
cout << "Total Pairs = " << count << "\n" ;
}
int main()
{
int arr[] = { 3, 5, 7, 5, 1, 9, 9 };
int k = 12;
int n = sizeof (arr) / sizeof (arr[0]);
pairs(arr, n, k);
return 0;
}
|
Python3
from sys import maxsize
from bisect import bisect_left, bisect_right
def pairs(arr, n, k):
smallest = maxsize
count = 0
s = set ()
s.add(arr[ 0 ])
for i in range ( 1 , n):
sorted_s = sorted (s)
index = bisect_left(sorted_s, k - arr[i])
if index = = len (sorted_s):
lower = sorted_s[index - 1 ]
else :
lower = sorted_s[index]
index = bisect_right(sorted_s, k - arr[i])
if index = = len (sorted_s):
upper = sorted_s[index - 1 ]
else :
upper = sorted_s[index]
curr_min = min ( abs (lower + arr[i] - k), abs (upper + arr[i] - k))
if curr_min < smallest:
smallest = curr_min
count = 1
elif curr_min = = smallest:
count + = 1
s.add(arr[i])
print ( "Minimal Value = " , smallest)
print ( "Total Pairs = " , count)
arr = [ 3 , 5 , 7 , 5 , 1 , 9 , 9 ]
k = 12
n = len (arr)
pairs(arr, n, k)
|
Java
import java.util.*;
class Main {
static void pairs( final int [] arr, final int n, final int k) {
int smallest = Integer.MAX_VALUE, count = 0 ;
Set<Integer> s = new TreeSet<>();
s.add(arr[ 0 ]);
for ( int i = 1 ; i < n; i++) {
int lower = Integer.MIN_VALUE;
int upper = Integer.MAX_VALUE;
for (Integer x : s) {
if (x <= (k - arr[i]) && x >= lower) {
lower = x;
}
if (x >= (k - arr[i]) && x <= upper) {
upper = x;
}
}
int curr_min = Math.min(Math.abs(lower + arr[i] - k), Math.abs(upper + arr[i] - k));
if (curr_min < smallest) {
smallest = curr_min;
count = 1 ;
}
else if (curr_min == smallest)
count++;
s.add(arr[i]);
}
System.out.println( "Minimal Value = " + smallest);
System.out.println( "Total Pairs = " + count);
}
public static void main(String[] args) {
int [] arr = { 3 , 5 , 7 , 5 , 1 , 9 , 9 };
int k = 12 ;
int n = arr.length;
pairs(arr, n, k);
}
}
|
Javascript
function pairs(arr, n, k) {
let smallest = Number.MAX_SAFE_INTEGER;
let count = 0;
let s = new Set();
s.add(arr[0]);
for (let i = 1; i < n; i++) {
let lower = [...s].find((element) => element >= k - arr[i]);
let upper = [...s].find((element) => element >= k - arr[i]);
let curr_min = Math.min(Math.abs(lower + arr[i] - k), Math.abs(upper + arr[i] - k));
if (curr_min < smallest) {
smallest = curr_min;
count = 1;
}
else if (curr_min === smallest)
count++;
s.add(arr[i]);
}
console.log(`Minimal Value = ${smallest}`);
console.log(`Total Pairs = ${count}`);
}
let arr = [3, 5, 7, 5, 1, 9, 9];
let k = 12;
let n = arr.length;
pairs(arr, n, k);
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void pairs( int [] arr, int n, int k)
{
int smallest = int .MaxValue, count = 0;
SortedSet< int > s = new SortedSet< int >();
s.Add(arr[0]);
for ( int i = 1; i < n; i++)
{
int lower = s.Where(e => e >= k - arr[i]).DefaultIfEmpty( int .MinValue).First();
int upper = s.Where(e => e > k - arr[i]).DefaultIfEmpty( int .MaxValue).First();
int curr_min = Math.Min(Math.Abs(lower + arr[i] - k), Math.Abs(upper + arr[i] - k));
if (curr_min < smallest)
{
smallest = curr_min;
count = 1;
}
else if (curr_min == smallest)
{
count++;
}
s.Add(arr[i]);
}
Console.WriteLine( "Minimal Value = " + smallest);
Console.WriteLine( "Total Pairs = " + count);
}
static void Main( string [] args)
{
int [] arr = { 3, 5, 7, 5, 1, 9, 9 };
int k = 12;
int n = arr.Length;
pairs(arr, n, k);
}
}
|
OutputMinimal Value = 0
Total Pairs = 4
Time Complexity : O(n Log n)
Auxiliary Space: O(n)
This article is contributed by Shivam Pradhan . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.