I recently had to do a code challenge where I was instructed that for a set of numbers, find the number of pairs whose difference was K. For example, given then numbers 1, 5, 3, 4, 2
, and the difference K (2) there are 3 pairs: (5,3) (4,2) (3,1). I tried this challenge in PHP. My code passed the test, but was inefficient i guess because some of the test timed out. Can anyone tell me how I could have improved it? I'm bashing my head because I can't figure out how I could make it more efficient.
Here's my code
<?php
// Open STDIN for reading
$stdin = fopen('php://stdin', 'r');
// Get the input
while(!feof($stdin)) {
$inputs[] = explode(' ', fgets($stdin));
}
fclose($handle);
$k = $inputs[0][1];
$values = array_map('intval', array_values($inputs[1]));
// Sort in decending order
rsort($values);
// Given the difference, K, find a pair for $left within
// $right whose difference is K
function findPair($k, $left, $right){
foreach($right as $n) {
if($left - $n == $k)
return $n;
// If the difference is greater than $k, there is no pair
if($left - $n > $k)
return false;
}
return false;
}
$pairs = 0;
while(count($values) > 1){
$left = array_shift($values);
$n = findPair($k, $left, $values);
if($n !== false)
$pairs++;
}
echo $pairs;
?>