Skip to content

Instantly share code, notes, and snippets.

@stahnni
Created May 11, 2017 17:41
Show Gist options
  • Save stahnni/286d488b7b21fae87ff6949f21d02b74 to your computer and use it in GitHub Desktop.
Save stahnni/286d488b7b21fae87ff6949f21d02b74 to your computer and use it in GitHub Desktop.
adjacentElementsProduct from codefights
/*
Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
Example
For inputArray = [3, 6, -2, -5, 7, 3], the output should be
adjacentElementsProduct(inputArray) = 21.
7 and 3 produce the largest product.
Input/Output
[time limit] 4000ms (js)
[input] array.integer inputArray
An array of integers containing at least two elements.
Guaranteed constraints:
2 ≤ inputArray.length ≤ 10,
-1000 ≤ inputArray[i] ≤ 1000
*/
function adjacentElementsProduct(inputArray) {
// //declare a varaible to store the result of the computation
// var result = inputArray[0];
// //we need a loop to loop hrough the array and multiply adjacent numbers
// for(var i = 1; i < inputArray.length; i++) {
// result *= inputArray[i];
// }
//
if (inputArray.length == 1) return 0;
var maxProduct = inputArray[0] * inputArray[1];
for(var i = 0; i < inputArray.length - 1; i++) {
if(inputArray[i] * inputArray[i+1] > maxProduct) {
maxProduct = inputArray[i] * inputArray[i+1];
}
}
return maxProduct;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment