Created
July 27, 2020 17:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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]] --> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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