🔷 Adjacent Elements Product challenge:
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
solution(inputArray) = 21
.
7
and 3
produce the largest product.
Input/Output
[execution time limit] 3 seconds (java)
[memory limit] 1 GB
[input] array.integer inputArray
An array of integers containing at least two elements.
Guaranteed constraints:
2 ≤ inputArray.length ≤ 10
,
-1000 ≤ inputArray[i] ≤ 1000
.
[output] integer
The largest product of adjacent elements.
JS solution
function solution ( inputArray ) {
var maxProduct = inputArray [ 0 ] * inputArray [ 1 ]
for ( var i = 2 ; i < inputArray . length ; i ++ ) {
let currentProduct = inputArray [ i ] * inputArray [ i - 1 ]
maxProduct = currentProduct > maxProduct ? currentProduct : maxProduct
}
return maxProduct ;
}
var inputArray = [ 1 , 0 , 1 , 0 , 1000 ]
console . log ( `The max adjacent numbers product in the array [${ inputArray } ] is ${ solution ( inputArray ) } ` )
var inputArray2 = [ 3 , 6 , - 2 , - 5 , 7 , 3 ] ;
console . log ( "The max adjacent numbers product in the array %s is %d" , inputArray2 , solution ( inputArray2 ) )
Java solution
import java .util .Arrays ;
public class Adjacent_elements_product {
public static void main (String args []){
int testArray [] = new int [] {3 , 6 , -2 , -5 , 7 , 3 };
System .out .format (" The max adjacent numbers product for the array %s is %d %n" , Arrays .toString (testArray ), solution (testArray ));
int testArray2 [] = new int [] {1 , 0 , 1 , 0 , 1000 };
System .out .format (" The max adjacent numbers product for the array %s is %d %n" , Arrays .toString (testArray2 ), solution (testArray2 ));
}
static int solution (int [] inputArray ) {
int maxProduct = inputArray [0 ]*inputArray [1 ];
for (int i = 2 ; i <inputArray .length ; i ++){
int currentProduct = inputArray [i ]* inputArray [i -1 ];
if (currentProduct > maxProduct )
maxProduct = currentProduct ;
}
return maxProduct ;
}
}