Possible Solution
Here’s one way to solve the problem:
function findClosestPair($arr, $target) {
$n = count($arr);
$minDiff = PHP_INT_MAX;
$result = [];
// Sort the array in non-descending order
sort($arr);
// Initialize two pointers
$left = 0;
$right = $n - 1;
while ($left < $right) {
$sum = $arr[$left] + $arr[$right];
$diff = abs($sum - $target);
// If the sum is equal to the target, we have found a pair
if ($sum == $target) {
$result = [$arr[$left], $arr[$right]];
break;
}
// Update the closest pair if necessary
if ($diff < $minDiff) {
$minDiff = $diff;
$result = [$arr[$left], $arr[$right]];
}
// Move the pointers
if ($sum < $target) {
$left++;
} else {
$right--;
}
}
return $result;
}
The function first sorts the input array in non-descending order using the sort()
function. It then initializes two pointers, left
and right
, to the start and end of the array, respectively. It then loops through the array using the two pointers, calculating the sum of the current pair and comparing it to the target value.
If the sum is equal to the target, the function immediately returns the pair. If the absolute difference between the sum and the target is smaller than the current minimum difference, the function updates the result to the current pair. Finally, the function moves the pointers based on whether the sum is less than or greater than the target.
At the end of the loop, the function returns the closest pair found.