Skip to content

Instantly share code, notes, and snippets.

@geggleto
Created October 5, 2017 01:21
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 geggleto/a93e5d1876f9c2ce545a2c243c6d220a to your computer and use it in GitHub Desktop.
Save geggleto/a93e5d1876f9c2ce545a2c243c6d220a to your computer and use it in GitHub Desktop.
//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