Given An Array Of Integers, Find The Pair Of Adjacent Elements That Has The Largest Product And Return That Product
Solution 1:
You could start with a really large negative value, instead of zero.
var p = -Infinity;
Solution 2:
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;
functionadjacentElementsProduct(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]));
Solution 3:
This is quite simple actually
functionadjacentElementsProduct(inputArray) {
let max = -Infinity;
for (let i = 1; i < inputArray.length; i++) {
max = Math.max(inputArray[i] * inputArray[i - 1], max);
}
returnmax;
}
Solution 4:
Here's a very simple implementation without using any additional variables (actually less), and no special values. Just simple logic.
functionadjacentElementsProduct(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. :)
Solution 5:
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:
staticvoidMain(string[] args)
{
int[] arr = { 1, -4, 3, -6, -7, 0 };
Console.WriteLine(FindMaxProduct(arr));
Console.ReadKey();
}
staticintFindMaxProduct(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;
}
Post a Comment for "Given An Array Of Integers, Find The Pair Of Adjacent Elements That Has The Largest Product And Return That Product"