Closest product pair in an array
Last Updated :
29 Mar, 2024
Given an array of non-negative integers and a number x, find a pair in the array whose product is closest to x.
Examples:
Input : arr[] = [2, 3, 5, 9]
x = 47
Output : {5, 9}
Input : arr[] = [2, 3, 5, 9]
x = 8
Output : {2, 5}
Method 1
A simple solution is to consider every pair and keep track of the closest pair (absolute difference between pair product and x is minimum). Finally, print the closest pair. The time complexity of this solution is O([Tex]n^2 [/Tex])
Implementation:-
C++
#include <bits/stdc++.h>
using namespace std;
void printClosest( int arr[], int n, int x)
{
pair< int , int > ans;
int temp = INT_MAX;
for ( int i = 0; i < n - 1; i++) {
for ( int j = i + 1; j < n; j++) {
if ( abs (arr[i] * arr[j] - x) <= temp) {
ans.first = arr[i];
ans.second = arr[j];
temp = abs (arr[i] * arr[j] - x);
}
}
}
cout << ans.first << " " << ans.second;
}
int main()
{
int arr[] = { 2, 3, 5, 9 }, x = 8;
int n = sizeof (arr) / sizeof (arr[0]);
printClosest(arr, n, x);
return 0;
}
|
Java
public class Main {
public static void printClosest( int [] arr, int n, int x)
{
int closestFirst = 0 , closestSecond = 0 ;
int temp = Integer.MAX_VALUE;
for ( int i = 0 ; i < n - 1 ; i++) {
for ( int j = i + 1 ; j < n; j++) {
if (Math.abs(arr[i] * arr[j] - x) <= temp) {
closestFirst = arr[i];
closestSecond = arr[j];
temp = Math.abs(arr[i] * arr[j] - x);
}
}
}
System.out.println(closestFirst + " "
+ closestSecond);
}
public static void main(String[] args)
{
int [] arr = { 2 , 3 , 5 , 9 };
int x = 8 ;
int n = arr.length;
printClosest(arr, n, x);
}
}
|
Python3
def printClosest(arr: list , n: int , x: int ):
ans_a, ans_b = 0 , 0
temp = float ( "inf" )
for i in range (n - 1 ):
for j in range (i + 1 , n):
if abs (arr[i] * arr[j] - x) < = temp:
ans_a, ans_b = arr[i], arr[j]
temp = abs (arr[i] * arr[j] - x)
print (ans_a, ans_b)
arr = [ 2 , 3 , 5 , 9 ]
x = 8
n = len (arr)
printClosest(arr, n, x)
|
C#
using System;
namespace ClosestPair
{
class Program
{
static void PrintClosest( int [] arr, int n, int x)
{
int closestFirst = 0, closestSecond = 0;
int temp = int .MaxValue;
for ( int i = 0; i < n - 1; i++)
{
for ( int j = i + 1; j < n; j++)
{
if (Math.Abs(arr[i] * arr[j] - x) <= temp)
{
closestFirst = arr[i];
closestSecond = arr[j];
temp = Math.Abs(arr[i] * arr[j] - x);
}
}
}
Console.WriteLine(closestFirst + " " + closestSecond);
}
static void Main( string [] args)
{
int [] arr = { 2, 3, 5, 9 };
int x = 8;
int n = arr.Length;
PrintClosest(arr, n, x);
}
}
}
|
Javascript
<script>
function printClosest(arr, n, x){
var temp = 1e9;
var a, b;
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
if (Math.abs(arr[i] * arr[j] - x) <= temp) {
a= arr[i];
b=arr[j];
temp = Math.abs(arr[i] * arr[j] - x);
}
}
}
console.log(a , b);
}
const arr=[2, 3, 5, 9];
const n = arr.length;
const x =8;
printClosest(arr, n, x);
<script>
|
Time Complexity:- O(N^2)
Auxiliary Space:- O(1)
Method 2: O(n Log n)
- Sort the array
- Initialize a variable diff as infinite (Diff is used to store the difference between a pair and x). We need to find the minimum diff.
- Traverse the array and for each i, do the following :
- Find the lower bound for x/arr[i] in the sub-array on the right of arr[i], i.e., in subarray arr[i+1..n-1]. Let it be denoted by l.
- Find the upper bound for x/arr[i] in the sub array on the right of arr[i], i.e., in sub array arr[i+1..n-1]. Let it be denoted by u.
- If min(abs((arr[i] * l) – x), abs((arr[i] * u) – x)) < diff, then update diff and result
Method 3 O(n for sorted)
An efficient solution can find the pair in O(n) time. The following is the detailed algorithm.
1) Initialize a variable diff as infinite
(Diff is used to store the difference
between pair and x). We need to find
the minimum diff.
2) Initialize two index variables l and r
in the given sorted array.
(a) Initialize first to the leftmost index:
l = 0
(b) Initialize second the rightmost index:
r = n-1
3) Loop while l < r.
(a) If abs((arr[l] * arr[r]) - x) < diff
then update diff and result
(b) Else if((arr[l] * arr[r]) < x) then
l++
(c) Else r--
The following is the implementation of the above algorithm.
C++
#include <bits/stdc++.h>
using namespace std;
void printClosest( int arr[], int n, int x)
{
int res_l, res_r;
int l = 0, r = n - 1, diff = INT_MAX;
while (r > l) {
if ( abs (arr[l] * arr[r] - x) < diff) {
res_l = l;
res_r = r;
diff = abs (arr[l] * arr[r] - x);
}
if (arr[l] * arr[r] > x)
r--;
else
l++;
}
cout << " The closest pair is "
<< arr[res_l] << " and " << arr[res_r];
}
int main()
{
int arr[] = { 2, 3, 5, 9 }, x = 8;
int n = sizeof (arr) / sizeof (arr[0]);
printClosest(arr, n, x);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void printClosest( int arr[],
int n, int x)
{
int res_l = 0 , res_r = 0 ;
int l = 0 , r = n - 1 , diff = Integer.MAX_VALUE;
while (r > l)
{
if (Math.abs(arr[l] * arr[r] - x) < diff)
{
res_l = l;
res_r = r;
diff = Math.abs(arr[l] * arr[r] - x);
}
if (arr[l] * arr[r] > x)
r--;
else
l++;
}
System.out.print( "The closest pair is " );
System.out.print (arr[res_l] +
" and " +
arr[res_r]);
}
public static void main (String[] args)
{
int arr[] = { 2 , 3 , 5 , 9 };
int x = 8 ;
int n = arr.length;
printClosest(arr, n, x);
}
}
|
Python3
import sys
def printClosest(arr, n, x):
res_l = 0 ;
res_r = 0 ;
l = 0 ;
r = n - 1 ;
diff = sys.maxsize;
while (r > l):
if ( abs (arr[l] *
arr[r] - x) < diff):
res_l = l;
res_r = r;
diff = abs (arr[l] *
arr[r] - x);
if (arr[l] * arr[r] > x):
r = r - 1 ;
else :
l = l + 1 ;
print ( "The closest pair is" , arr[res_l] ,
"and" , arr[res_r]);
arr = [ 2 , 3 , 5 , 9 ];
x = 8 ;
n = len (arr);
printClosest(arr, n, x);
|
C#
using System;
class GFG
{
static void printClosest( int []arr,
int n, int x)
{
int res_l = 0, res_r = 0;
int l = 0, r = n - 1,
diff = int .MaxValue;
while (r > l)
{
if (Math.Abs(arr[l] *
arr[r] - x) < diff)
{
res_l = l;
res_r = r;
diff = Math.Abs(arr[l] *
arr[r] - x);
}
if (arr[l] * arr[r] > x)
r--;
else
l++;
}
Console.Write( "The closest pair is " );
Console.Write (arr[res_l] +
" and " +
arr[res_r]);
}
public static void Main ()
{
int []arr = {2, 3, 5, 9};
int x = 8;
int n = arr.Length;
printClosest(arr, n, x);
}
}
|
PHP
<?php
function printClosest( $arr , $n , $x )
{
$res_l ; $res_r ;
$l = 0; $r = $n - 1; $diff = PHP_INT_MAX;
while ( $r > $l )
{
if ( abs ( $arr [ $l ] *
$arr [ $r ] - $x ) < $diff )
{
$res_l = $l ;
$res_r = $r ;
$diff = abs ( $arr [ $l ] *
$arr [ $r ] - $x );
}
if ( $arr [ $l ] * $arr [ $r ] > $x )
$r --;
else
$l ++;
}
echo " The closest pair is " ,
$arr [ $res_l ] , " and " ,
$arr [ $res_r ];
}
$arr = array (2, 3, 5, 9);
$x = 8;
$n = count ( $arr );
printClosest( $arr , $n , $x );
?>
|
Javascript
<script>
function printClosest(arr, n, x)
{
var res_l, res_r;
var l = 0, r = n - 1, diff = 10000000000;
while (r > l) {
if (Math.abs(arr[l] * arr[r] - x) < diff) {
res_l = l;
res_r = r;
diff = Math.abs(arr[l] * arr[r] - x);
}
if (arr[l] * arr[r] > x)
r--;
else
l++;
}
document.write( " The closest pair is "
+ arr[res_l] + " and " + arr[res_r]);
}
var arr = [2, 3, 5, 9 ], x = 8;
var n = arr.length;
printClosest(arr, n, x);
</script>
|
Output The closest pair is 2 and 5
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...