本文介绍了给定整数数组,找到具有最大乘积的相邻元素对并返回该乘积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个整数数组,找到具有最大乘积的相邻元素对并返回该乘积。



这是我的代码

 函数neighborElementsProduct(inputArray){
var arr = inputArray;
var x = 0;
var y = 0;
var p = 0;
for(var i = 0; i x = arr [i];
y = arr [i + 1];
if(x * y&p; p){
p = x * y;
};
};
return p;
};

问题是所有测试都能正常工作,但带有负积的数组除外中显示的 strong>可以帮助任何人..并预先感谢



解决方案

您可以

  var p = -Infinity; 

  var p = -Infinity; 


Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.

and here is my code

function adjacentElementsProduct(inputArray) {
 var arr = inputArray;
  var x=0;
  var y=0;
  var p=0;
  for(var i=0;i<arr.length;i++){
    x=arr[i];
    y=arr[i+1];
    if(x*y>p){
     p=x*y;
    };
  };
 return p;
};

the problem is all the tests works fine but except the array with the negative product as it shown in the attached photocan anyone help .. and thanks in advance

enter image description here

解决方案

You could start with a really large negative value, instead of zero.

var p = -Infinity;

这篇关于给定整数数组,找到具有最大乘积的相邻元素对并返回该乘积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 07:40