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

前端 未结 5 2026
情书的邮戳
情书的邮戳 2021-01-19 12:22

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 ad         


        
5条回答
  •  猫巷女王i
    2021-01-19 12:43

    You can try to create a new array of length (arr.length-1) inside the function and append the products of adjacent numbers to this new array. Then find the largest number in the array and return it. This will solve the problem with negative product.

    function adjacentElementsProduct(inputArray) {
      var arr = inputArray;
      var prodArr[];
      var p;
      for (var i = 0; i < arr.length-1; i++) {
        prodArr[i] = arr[i]*arr[i+1];
      };
      for (j=prodArr.length; j--){
      if (prodArr[j] > p) {
          p = prodArr[j];
        };
      return p;
    };
    
    console.log(adjacentElementsProduct([-23, 4, -3, 8, -12]));
    

提交回复
热议问题