Fady Safwat
Fady Safwat

Reputation: 93

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

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 photo can anyone help .. and thanks in advance

enter image description here

Upvotes: 9

Views: 38988

Answers (22)

Jatin Allamsetty
Jatin Allamsetty

Reputation: 1

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

def solution(inputArray):
    """ There should be a docstring here.
        All the more so with a name as non-suggestive as "solution".
    """
    l=[]
    for i in range(0,len(inputArray)-1):
        res=inputArray[i]*inputArray[i+1]
        #print(res)
        l.append(res)
    return max(l)

Here, we are storing all the adjacent product values in the list variable 'l' and return maximum of 'l' i.e.., largest adjacent pair product from the array.

Upvotes: 0

aboud_tr
aboud_tr

Reputation: 1

func solution(inputArray []int) int {
length := len(inputArray)
maxProduct := inputArray[0] * inputArray[1]

for i := 1; i < length-1; i++ {
    product := inputArray[i] * inputArray[i+1]
    if product > maxProduct {
        maxProduct = product
    }
}
return maxProduct}

OR

func solution(inputArray []int) int {
length := len(inputArray)
maxProduct := 0

for i := 0; i < length-1; i++ {
    product := inputArray[i] * inputArray[i+1]
    if product > maxProduct || i==0 {
        maxProduct = product
    }
}
return maxProduct}

First Method: Start with the product of the first two numbers in the list. Check each pair of adjacent numbers in the list. If a pair's product is greater than the current maximum product, update the maximum product. This method ensures we begin with a meaningful value for the maximum product, based on the initial pair of numbers.

Second Method: Begin with a default maximum product set to 0. Examine each pair of adjacent numbers in the list. If a pair's product is greater than the current maximum product or it's the first pair being considered, update the maximum product. This method relies on handling the first pair separately, ensuring it's always included in the consideration for the maximum product.

Upvotes: 0

ABDUL WAHAB
ABDUL WAHAB

Reputation: 1

Here is the better solution if you want to find the max product of the adjacent numbers using Typescript. Guaranteed constraints: 2 ≤ inputArray.length ≤ 10 -1000 ≤ inputArray[i] ≤ 1000

function maxAdjacentProduct(inputArray: number[]): number {
    let maxProduct: number;
    for(let i = 0; i < inputArray.length - 1; i++) {
        let currentProduct: number = inputArray[i] * inputArray[i + 1]
        if(maxProduct === undefined || maxProduct < currentProduct) {
            maxProduct = currentProduct
        }
    }
    return maxProduct;
}

Upvotes: 0

Darragh Blake
Darragh Blake

Reputation: 248

Here is a solution in PHP that is quite simple.

function solution($inputArray) {

$largest = null;
$pos = null;

for($i = 0; $i < count($inputArray) -1; $i++){
    $pos = ($inputArray[$i] * $inputArray[$i+1]);
    if($largest < $pos){
        $largest = $pos;
    }
}
return $largest ?? 0;

}

Upvotes: 0

user19274126
user19274126

Reputation:

python solution

You can make a loop from 1 to end of your list and do the following arithmetic operations

def solution(inputArray):
    list1 =[]
    for i in range(1,len(inputArray)):
        list1.append(inputArray[i]*inputArray[i-1]) 
    return max(list1)

Upvotes: 0

In Javascript, you could use the reduce method from an array to avoid iterating in a for loop, just like this.

function solution(inputArray) {
    let maxProd = []

    inputArray.reduce((accumulator, currentValue) => {
        maxProd.push(accumulator*currentValue)
        
        return currentValue
    },
    );

    return Math.max(...maxProd)
}

Once you have in the maxProd array the products, you use the spread operator to get the numbers and using Math.max() you get the largest

Upvotes: 0

Avag Sargsyan
Avag Sargsyan

Reputation: 11

Problem: Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. #javascript #arraymethods

function solution(inputArray) {
    let productsArr = []; // to hold the products of adjacent elements
    let n = 0;
    for (let i = 0; i < inputArray.length; i++) {
        if (i < inputArray.length - 1) 
        {
            productsArr[n] = inputArray[i] * inputArray[i + 1];
            n++;
        }
    }
    return productsArr.reduce((aggr, val) => Math.max(aggr, val)); // to find out the biggest product
}

Upvotes: 1

I had the same problem at first, defining the first max as 0. Then i came up with this:

function solution(inputArray) {
    let products = inputArray.map(function(x, index){
        return inputArray[index+1] != undefined? x *inputArray[index+1] : -Infinity;
    })
    return Math.max(...products);
}

Upvotes: 1

Yusuf Raza
Yusuf Raza

Reputation: 55

import 'dart:math';

int solution(List<int> inputArray) {
    //assumption for highest number 
    int highestNumber  = inputArray[0] * inputArray[1] ;
    
    //we'll go through the array to campare the highestNumber
    //with next index
    for(var i = 1 ; i < inputArray.length ; i++){
      highestNumber = max(highestNumber,  inputArray[i] * inputArray[i - 1]);
    }
    return highestNumber;
}

Upvotes: 0

Bassam Khafgy
Bassam Khafgy

Reputation: 1

//Kotlin
fun solution(inputArray: MutableList<Int>): Int {
    var result: Int = Int.MIN_VALUE
    for (i in 0..inputArray.size - 2) {
        if (inputArray[i] * inputArray[i + 1] > result)
            result = inputArray[i] * inputArray[i + 1]
    }
    return result
}

Upvotes: 0

gelila
gelila

Reputation: 1

    function solution(inputArray) {
     let first, second, sum = []
    inputArray.map((arr,index)=>{ 
        first = arr;
        second =  inputArray[index+1]
        if(second == undefined){
            return second
        }
     return sum.push(first * second)
    })
   
  let last =  sum.sort().reduce((pre,next)=> {
     return pre > next ? pre : next
    })
    return last;
}

Upvotes: 0

Cristian Castillo
Cristian Castillo

Reputation: 11

function solution(inputArray: number[]): number {
    var max = -Infinity;
    
    for(var i=0; i+1<inputArray.length; i++)
    {
        if(max<(inputArray[i]*inputArray[i+1])){
            max=inputArray[i]*inputArray[i+1];
        }
    }
    return max;
}

console.log(solution([2,3,6]))

Upvotes: 1

Anon Kaedsalung
Anon Kaedsalung

Reputation: 21

This is quite simple actually

const solution = (inputArray) => Math.max(...inputArray.slice(0, -1).map((n, index) => n * inputArray[index + 1]))

console.log(solution([3, 6, -2, -5, 7, 3]))

Upvotes: 2

ncutixavier
ncutixavier

Reputation: 651

function solution(inputArray) {
    let f, s, arr = []
    for(let i=0; i<inputArray.length; i++){
        f = inputArray[i]
        s = inputArray[i+1]
        arr.push(f*s)
    }
    let max = arr.sort((a, b) => b - a)
    return max[0]
}

console.log(solution([3, 6, -2, -5, 7, 3]))

Upvotes: -1

ANUSHIYA ASOKAN
ANUSHIYA ASOKAN

Reputation: 1

you can try to initialize a integer as negative infinity value -math.inf and then use the python ternary operator var=true if condition else false to find the maximum value

code in python

def adjacentarray(a):
    maximum=-math.inf
    for i,in range(0,len(a)-1):
        maximum=a[i]*a[i+1] if a[i]*a[i+1]>maximum else maximum
    return maximum

code in javascript

function adjacentElementsProduct(a) {
    var maximum=-Infinity;
    for (var i=0;i<a.length-1;i++){
        maximum= a[i]*a[i+1]>maximum?a[i]*a[i+1]:maximum;
    }
    return maximum;
}

Upvotes: 0

inputarray
inputarray

Reputation: 11

This should help, wrote it in python. Concept: Pass an empty list, for every consecutive product keep storing it in the list. Then just return the max value.

def consecutive_product_max(a):
    lst2 = []
    for i in range(0, len(a)-1):
        x = a[i] * a[i+1]
        lst2.append(x)
    return max(lst2)

Upvotes: -1

Erinzzc
Erinzzc

Reputation: 1

The var p which saves the max product should be initialized as small as possible instead of a 0. So that when the product is negative, it will still meet the if condition and save the value. Here is a C# solution:

 static void Main(string[] args)
        {
            int[] arr = { 1, -4, 3, -6, -7, 0 };
            Console.WriteLine(FindMaxProduct(arr));
            Console.ReadKey();
        }
 static int FindMaxProduct(int[] arr) {
            int currentProduct = 0;
            int maxProduct = int.MinValue;
            int a=0, b = 0;
            for (int i = 0, j = i + 1; i < arr.Length - 1 && j < arr.Length; i++, j++)
            {
                currentProduct = arr[i] * arr[j];
                if (currentProduct>maxProduct) {
                    a = arr[i];
                    b = arr[j];
                    maxProduct = currentProduct;
                }
            }
            Console.WriteLine("The max product is {0}, the two nums are {1} and {2}.",maxProduct,a,b);
            return maxProduct;
        }

Upvotes: -1

0xcaff
0xcaff

Reputation: 13681

This is quite simple actually

function adjacentElementsProduct(inputArray) {
    let max = -Infinity;
    for (let i = 1; i < inputArray.length; i++) {
        max = Math.max(inputArray[i] * inputArray[i - 1], max);
    }

    return max;
}

Upvotes: 3

Aakash Choubey
Aakash Choubey

Reputation: 436

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<inputArray.length;i++){
        console.log(c);
        var c=inputArray[i]*inputArray[i+1];
        if(c > 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. :)

Upvotes: 0

Sarvesh Redkar
Sarvesh Redkar

Reputation: 113

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]));

Upvotes: -1

Nisarg Shah
Nisarg Shah

Reputation: 14541

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]));

Upvotes: 4

Nina Scholz
Nina Scholz

Reputation: 386550

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

var p = -Infinity;

Upvotes: 6

Related Questions