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

前端 未结 5 1971
情书的邮戳
情书的邮戳 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条回答
  •  醉梦人生
    2021-01-19 12:58

    You are initializing the variable p to zero. That means any multiplication values smaller than that are not accepted. Rather set it to the smallest possible integer value:

    var p = Number.MIN_SAFE_INTEGER;
    

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

提交回复
热议问题