Adjacent elements product

Description


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] boolean

The largest product of adjacent elements.

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
    console.log("This prints to the console when you Run Tests");
    return "Hello, " + name;
}

Solution


1
2
3
function adjacentElementsProduct(inputArray) {
    return Math.max(...inputArray.map((el,i)=>[el,inputArray[(i+1)%inputArray.length]]).slice(0,-1).map(([a,b])=>a*b));
}