DSA continued: adjacentElementsProduct
Let’s take a look at a slightly more difficult DSA question. In order to answer this question, we’d have to do some critical thinking, and also break down our code into multiple functions to separate our concerns and make the code easier to read and understand. Here’s the question:
Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
First, let’s create a function called getAdjacent. This function’s purpose will only return the product of two array indices that are side by side.
function getAdjacent(inputArray, index) {
return inputArray[index] * inputArray[index + 1];
}
Next, we define a new function called adjacentElementsProduct (or whatever you like). This is where we will call the previous function that we just defined. Also, this function will need to take an argument. We’ll call this argument inputArray.
function adjacentElementsProduct(inputArray) {
}
Next, we create a variable maxAdjacent equal to index 0 and index 1.
function adjacentElementsProduct(inputArray) {
let maxAdjacent = inputArray[0] * inputArray[1];
}
We’ll create a for loop that loops over the entire array, so we need to subtract the length of the array by one.
function adjacentElementsProduct(inputArray) {
let maxAdjacent = inputArray[0] * inputArray[1];
for (let i = 1; i < inputArray.length - 1; i++) {
}
}
This is where it gets tricky. Within the for loop, we’ll use an if statement. If getAdjacent is GREATER than the maxAdjacent variable that we set earlier, we’ll return those pairs of indices. If not, we’ll just return the maxAdjacent (which is the first and second index values of the array).
function adjacentElementsProduct(inputArray) {
let maxAdjacent = inputArray[0] * inputArray[1];
for (let i = 1; i < inputArray.length - 1; i++) {
if (getAdjacent(inputArray, i) > maxAdjacent) {
maxAdjacent = getAdjacent(inputArray, i);
}
}
return maxAdjacent;
}
In other words, we want to continue looping over the array if the product of the current two indices is smaller than the next two indices. Once we complete the entire array, we return the indices that have the greatest product. Happy coding!