Last active
October 23, 2019 10:41
-
-
Save HaiBV/b9a4d9b2c6ada6dd2820e65033f69ed2 to your computer and use it in GitHub Desktop.
adjacentElementsProduct.js
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
function adjacentElementsProduct(inputArray) { | |
var arrayLength = inputArray.length; | |
var largestProduct = inputArray[0] * inputArray[1]; | |
for (var i = 1; i < arrayLength - 1; i++) { | |
largestProduct = Math.max(largestProduct, inputArray[i] * inputArray[i + 1]); | |
} | |
return largestProduct; | |
} | |
function adjacentElementsProduct_short(arr) { | |
return Math.max(...arr.slice(1).map((x,i)=>[x*arr[i]])) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
[execution time limit] 4 seconds (js)
[input] array.integer inputArray
An array of integers containing at least two elements.
Guaranteed constraints:
2 ≤ inputArray.length ≤ 10,
-1000 ≤ inputArray[i] ≤ 1000.
[output] integer
The largest product of adjacent elements.