I came across a coding problem that goes as follows:
Given 2 sorted arrays: A and B, and a positive integer x, print the closest pair (one from each array) sum to x.
Example:
B = {10,20,30,40} , A = {0,4,6,11,11} , x = 13.
Output: 4 and 10.
This is what I've tried:
int i = 0;
int j = b.length - 1;
int closest = Integer.MAX_VALUE;
String s = "";
while (i <= a.length - 1 && j >= 0)
{
if (Math.abs((b[j] + a[i]) - x) < closest || Math.abs((b[j] + a[i]) - x) == 0)
{
closest = Math.abs(x - (b[j] + a[i]));
s = a[i] + " " + "and" + " " + b[j];
if (j != 0)
j--;
}
if (Math.abs((b[j] + a[i]) - x) > closest || j == 0)
i++;
}
System.out.println(s);
This code works fine with most inputs I tested including the example mentioned above,
except when the input x is 70 then the output is 11 and 30, instead of 11 and 40.
What I'm trying to understand basically is when should I decrease j and when should I increment i so that the code works on every possible x input.
The solution must be O(n) time complexity.
Appreciate the help! (If you find mistakes in my English, please let me know, I'm trying to improve.)