Skip to content

Instantly share code, notes, and snippets.

@HaiBV
Last active October 23, 2019 10:41
Show Gist options
  • Save HaiBV/b9a4d9b2c6ada6dd2820e65033f69ed2 to your computer and use it in GitHub Desktop.
Save HaiBV/b9a4d9b2c6ada6dd2820e65033f69ed2 to your computer and use it in GitHub Desktop.
adjacentElementsProduct.js
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]]))
}
@HaiBV
Copy link
Author

HaiBV commented Oct 23, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment