Created
October 5, 2017 01:21
-
-
Save geggleto/a93e5d1876f9c2ce545a2c243c6d220a to your computer and use it in GitHub Desktop.
This file contains 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
//Problem: Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. | |
//[-23, 4, -3, 8, -12] | |
// -23 * 4 = -92 | |
// 4 * -3 = -12 | |
// -3 * 8 = -24 | |
// 8 * -12 = -96 | |
// Return -12 | |
//Loop N-1 times starting at pos 0 | |
function adjacentElementsProduct(array $inputArray) { | |
$largestTotal = null; | |
foreach ($inputArray as $key => $value) { //You loop over all elements. You should skip the last element. | |
$nextValue = $inputArray[$key + 1]; // <--- Undefined Offset at N-1 | |
$total = $value * $nextValue; // $value * null == 0 | |
if (!isset($largestTotal) || $total > $largestTotal) { // false || 0 > -12 ==> True | |
$largestTotal = $total; //0 | |
} | |
} | |
return $largestTotal; //0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment