简体   繁体   中英

Javascript: adjacent Elements Product algorithm

I'm trying to solve a basic javascript algorithm and i'm kinda stuck, here is the question:

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

Example

For inputArray = [3, 6, -2, -5, 7, 3], the output should be adjacentElementsProduct(inputArray) = 21.

7 and 3 produce the largest product.

Here is my code, i can't find the problem but in the tests it says that it returns null:

    function adjacentElementsProduct(inputArray) {
    var cb;
    for(var i=0;i<inputArray.length;i++){
      if(inputArray[i] !== inputArray[inputArray.length-1]){
        if(inputArray[i]*inputArray[i+1] > cb){
          cb = inputArray[i]*inputArray[i+1];
        }
      }
    }
  return cb;
  }

What is my problem and what i need to change?

What you ultimately want to do is iterate through the array excluding the last member, and compare a product of each current item with its next adjacent member to that of the largest one found thus far.

You can use .slice() and .reduce() for this.

 function adjacentElementsProduct(arr) { return arr.slice(0, -1) .reduce((max, n, i) => Math.max(max, n * arr[i + 1]), -Infinity) } console.log(adjacentElementsProduct([3, 6, -2, -5, 7, 3]));


An alternate solution would be to create an array of products using .map() after doing the same .slice() , and pass that array's members to Math.max .

 function adjacentElementsProduct(arr) { return Math.max(...arr.slice(0, -1).map((n, i) => n * arr[i + 1])) } console.log(adjacentElementsProduct([3, 6, -2, -5, 7, 3]));

Using reduce we can simplify the amount of code.

 var a = [3, 6, -2, -2, 7, 3].reduce(function(a, b, i, arr){ if (b*arr[i-1] > a) { a = b*arr[i-1]; } return a; }) console.log(a)

Since you need to use pairs of elements - you can just run through it and keep store maximum product value, something like this:

 function adjacentElementsProduct(items) { var product = 0; for (var i = 0; i < items.length - 1; i++) { product = Math.max(product, items[i] * items[i + 1]); } return product; } console.log(adjacentElementsProduct([3, 6, -2, -5, 7, 3]));

First of all, you could iterate from index 1 to the end and use i - 1 and i for adjacent elements. Then you could check if you are in iteration one and take the value or if the multiplication is greater then the old value, then assing the greater product.

 function adjacentElementsProduct(inputArray) { var cb, i; for (i = 1; i < inputArray.length; i++) { if (i === 1 || inputArray[i - 1] * inputArray[i] > cb) { cb = inputArray[i - 1] * inputArray[i]; } } return cb; } console.log(adjacentElementsProduct([3, 6, -2, -5, 7, 3]));

The problem with your code is you never initialized cb . So the comparison with cb is always invalid. Here is the correct version of your code -

 function adjacentElementsProduct(inputArray) { var cb = Number.NEGATIVE_INFINITY; for(var i=0;i<inputArray.length-1;i++){ if(inputArray[i]*inputArray[i+1] > cb){ cb = inputArray[i]*inputArray[i+1]; } } return cb; } console.log(adjacentElementsProduct([3, 6, -2, -5, 7, 7]))

More generic solution: This will work for every array with negatives and non negatives numbers.

int adjacentElementsProduct(int[] inputArray) {

    int length = inputArray.Length;
    int max = Number.NEGATIVE_INFINITY;

    for (int i = 0; i < length - 1; i++ ) {
        max = Math.Max(max, inputArray[i] * inputArray[i+1]);
    }

    return max;
}
int adjacentElementsProduct(std::vector<int> inputArray) {
    int n=inputArray.size();
 int p=1;
 int maxp=inputArray[0]*inputArray[1];
    for(int i=0;i<n-1;i++){
       p=inputArray[i]*inputArray[i+1]; 
       if(p>maxp){
           maxp=p;
       }       
    }
    
    return maxp;
}

Here is how you will do that in Python:

 def adjacentElementsProduct(inputArray):
    max = inputArray[0]* inputArray[1]
    for i in range(0, len(inputArray)-1):
            if inputArray[i] * inputArray[i+1] > max :
                max = inputArray[i] * inputArray[i+1]
                i+1
            else:
                i+1
    return max  

Or you can do it in one line like:

def adjacentElementsProduct(inputArray):
    return max([inputArray[i] * inputArray[i+1] for i in range(len(inputArray)-1)])

        
function largetProduct(inputArray) {
   let pairs=[];
     for(var i = 0;i<inputArray.length ;i+=2){
         pairs.push(inputArray.slice(i,i+2))
     }


    let products = pairs.map(v=> v[0]*v[1] || 1);
        return (Math.max.apply(0,products));
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM