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

前端 未结 5 1976
情书的邮戳
情书的邮戳 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 13:02

    Here's a very simple implementation without using any additional variables (actually less), and no special values. Just simple logic.

    function adjacentElementsProduct(inputArray) {
        var c =inputArray[0]*inputArray[1];
        var p = c;
        for(var i=1;i p){
                p=c;
            };
        };
        return p;
    };
    console.log("minimum product = " + adjacentElementsProduct([-23,4,-3,8,-12]));

    What I did was, initialize a variable c (current product) with the product of first two elements of the array. And then I declared the variable p and initialize it to c. This way, all other products are compared to this product. Rest is simple.

    Hope it helps. :)

提交回复
热议问题