Hi there :), our question for today is from code signal, and it’s an easy problem.

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.

https://app.codesignal.com/arcade/intro/level-2/xzKiBHjhoinnpdh6m

My way of approcahing this problem is an O(n) solution that loops through the array once with pointers at the current index element and next element (adjacent). We will never really have to check backwards, so increasing our pointers will work for this problem.

Let’s define a left and right pointer. The left pointer will start at position 0 and right will start at left+1; I would also like to set the current maximum adjacent value to -Infinity so we can replace that right away.

1 2 3 4 5 |
let currentLargest = -Infinity; let leftPointer = 0; let rightPointer = 1; |

Next, let’s check for when the given array has only two elements. We should probably return the product of those two elements so we exit early.

1 2 3 |
if (inputArray.length === 2) return inputArray[leftPointer] * inputArray[rightPointer]; |

Next we will define our loop through the array (once). While the left pointer is less than the right and right is less than or same as length of the array, if at any point the product of the element at the index of the left pointer and right pointer is greater than our currentLargest, we update currentLargest, and increment our pointers. In the end, we return currentLargest.

As you can see, this is a very easy problem and it will run in O(n) time, and constant space, O(1). Below is the full code;

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function adjacentElementsProduct(inputArray) { let currentLargest = -Infinity; let leftPointer = 0; let rightPointer = 1; if (inputArray.length === 2) return inputArray[leftPointer] * inputArray[rightPointer]; while(leftPointer < rightPointer && rightPointer <= inputArray.length) { if (inputArray[leftPointer] * inputArray[rightPointer] > currentLargest) { currentLargest = inputArray[leftPointer] * inputArray[rightPointer]; } leftPointer++; rightPointer++; } return currentLargest; } |

Do you have a suggestion on better approaches to the problem? Please feel free to share below. Cheers!