JavaScript:相邻元素乘积算法
我们得到一个整数数组。我们需要找到具有最大乘积的一对相邻元素并返回该乘积。
例如-
如果输入数组是-
const arr = [3, 6, -2, -5, 7, 3];
那么输出应该是21,因为[7,3]是总和最大的对。
示例
以下是代码-
const arr = [3, 6, -2, -5, 7, 3];
const adjacentElementsProduct = (arr = []) => {
let prod, ind;
for (ind = 1; ind < arr.length; ind++) {
if (ind === 1 || arr[ind - 1] * arr[ind] > prod) {
prod = arr[ind - 1] * arr[ind];
};
};
return prod;
};
console.log(adjacentElementsProduct(arr));输出结果以下是控制台上的输出-
21