Skip to content

Instantly share code, notes, and snippets.

@fokosun
Created July 27, 2020 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fokosun/9bb4ecedc14d5734c72cf906ce86ae9c to your computer and use it in GitHub Desktop.
Save fokosun/9bb4ecedc14d5734c72cf906ce86ae9c to your computer and use it in GitHub Desktop.
Write a function that returns a pair of numbers from the 2 arrays whose sum is the closest to the target
<!-- Given: two integer arrsya and a target which is just a number.
Write a function that returns a pair of numbers from the 2 arrays whose sum is the closest to the target
e.g ([-1, 3, 8, 2, 9, 5], [4, 1, 2, 10, 5, 20], 24))
should return [[3, 20], [5, 20]] -->
<?php
function sum_closest_to_target($s1 = [], $s2 = [], $t) {
$tl = $t - 1;
$tu = $t + 1;
$result = [];
for($i=0; $i<count($s1); $i++) {
for($j=0; $j<count($s2); $j++) {
if (($s1[$i] + $s2[$j] == $tl) || ($s1[$i] + $s2[$j] == $tu)) {
$result[] = [$s1[$i], $s2[$j]];;
}
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment