repl.it
@jonathanbell/

Add two largest integers in array

PHP (Legacy)

No description

fork
loading
main.php
1
2
3
4
5
6
7
8
9
10
11
12
13
// Please write a function (in either PHP or Javascript) that takes an array of integers as an argument, and efficiently returns the sum of the two largest elements in the array. For example, if the array passed in is [3, 17, 8, -20, 0], the return value should be 25. (17 + 8)

// Keep in mind that the array can be made up of any valid integers, and that the length of the array is unknown (but could potentially be very large).

function tempestFunction($arr) {
  $highestVal = max($arr);
  unset($arr[array_search($highestVal, $arr)]);
  $secondHighestVal = max($arr);

  return $highestVal + $secondHighestVal;
}

echo tempestFunction([3, 17, 8, -20, 0]).PHP_EOL;
PHP 7.0.8 (Legacy: use the following for new features: Command-line PHP: https://repl.it/languages/php_cli PHP Web Server: https://repl.it/languages/php7