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 = 14
  • a[1] + b[1] = 20 + 7 = 27
  • a[2] + b[2] = 11 + 1 = 12
  • a[3] + b[3] = 19 + 0 = 19
  • a[4] + b[4] = 33 + 10 = 43
  • a[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

  1. Java- Count number of pairs in the Array whose sum is zero
  2. Java- Find the index of the two numbers in the array whose sum is equal to a given number

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.