An Array of integers is given, both +ve and -ve. You need to find the two elements such that their sum is closest to target.
public static int[] findTwoSumClosest(int[] num, int target) {
if(num==null || num.length==0)
return null;
int[] result = new int[2];
Arrays.sort(num);
int start=0, end=num.length-1;
int closest = Integer.MAX_VALUE;
while(start<end){
int sum = num[start] + num[end];
int diff = Math.abs(target-sum);
if(diff<closest){
closest = diff;
result[0] = num[start];
result[1] = num[end];
}
if(sum>target)
end--;
else
start++;
}
return result;
}
public static void main(String[] args) {
int[] num = {1,60,-10,70,-80,85,95,79,-83};
int[] result = findTwoSumClosest(num,3);
System.out.print(result[0]+" "+result[1]);
}
Return [-83, 85]