Find the closest pair from Array to a target value in Java
Java- Find the closest pair from Array: In this blog, we’ll explore a common problem in algorithm development: finding the pair of elements from two integer arrays that, when summed together, are closest to a given target value.
int[] a = {12, 20, 11, 19, 33, 11};
int[] b = {2, 7, 1, 0, 10, 44};
int cloestTo = 30;
Desired Output: The sum of pair (20, 7)
is 27, and it is closest to the target value of 30.
Explanation:
a[0] + b[0]
= 12 + 2 = 14a[1] + b[1]
= 20 + 7 = 27a[2] + b[2]
= 11 + 1 = 12a[3] + b[3]
= 19 + 0 = 19a[4] + b[4]
= 33 + 10 = 43a[5] + b[5]
= 11 + 44 = 55
Among these, the closest sums to 30 are 27 (a[1] + b[1]
).
Constraint: Both arrays always have the same size.
ClosestPair.java
package org.websparrow;
public class ClosestPair {
public static void main(String[] args) {
int[] a = {12, 20, 11, 19, 33, 11};
int[] b = {2, 7, 1, 0, 10, 44};
int closestTo = 30;
findClosestPair(a, b, closestTo);
}
public static void findClosestPair(int[] a, int[] b, int closestTo) {
int closestSum = Integer.MAX_VALUE;
int closestA = 0;
int closestB = 0;
int minDiff = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++) {
int sum = a[i] + b[i];
int diff = Math.abs(closestTo - sum);
if (diff < minDiff) {
closestSum = sum;
closestA = a[i];
closestB = b[i];
minDiff = diff;
}
}
System.out.println("The pair closest to " + closestTo + " is: (" + closestA + ", " + closestB + ")");
System.out.println("Their sum is: " + closestSum);
}
}
Output:
console.log
The pair closest to 30 is: (20, 7)
Their sum is: 27
References
- Java- Count number of pairs in the Array whose sum is zero
- Java- Find the index of the two numbers in the array whose sum is equal to a given number