Adjacent Elements Product
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
adjacent_elements_product(inputArray) = 21
7
and 3
produce the largest product.
Solution
py
def adjacent_elements_product(inputArray):
return max(inputArray[i] * inputArray[i + 1] for i in range(len(inputArray) - 1))
print(adjacent_elements_product([3, 6, -2, -5, 7, 3]))
js
function adjacentElementsProduct(inputArray) {
let max = inputArray[0] * inputArray[1];
for (let i = 1; i < inputArray.length - 1; i++) {
const product = inputArray[i] * inputArray[i + 1];
if (product > max) {
max = product;
}
}
return max;
}
// we should output -12
console.log(adjacentElementsProduct([-23, 4, -3, 8, -12]));