Code Challenge: Adjacent Elements Product — In C

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 beadjacentElementsProduct(inputArray) = 21.
7 and 3 produce the largest product.
Input/Output
[execution time limit] 0.5 seconds (c)
[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.

Understand

We need to multiply all neighboring numbers and whichever gives us the largest number is the answer.

Plan

First things first, we need to multiply the number at the zero index by the number at the one index. That will be our initial “Max Value”. Then we need to loop through the array in order to multiply every number to its neighbor. Then return the largest. Probably will need a conditional that says something like, if these numbers multiplied is greater or equal to the current max, then that will be the new max. Then return the max.

Execute

#include <stddef.h>

int adjacentElementsProduct(arr_integer inputArray) {
    
// We need to multiply the number at the zero index by the number index.
    int max = inputArray.arr[0] * inputArray.arr[1];

    // That will be our initial max.
    int i;
    // Loop through the array in order to multiply every number to it's neighbor
    for(i = 1; i < inputArray.size-1; i++){
        // If these numbers multiplied is greater or equal to the current max
        if(inputArray.arr[i]*inputArray.arr[i+1]>=max){

            // Then that will be the new max
            max = inputArray.arr[i] * inputArray.arr[i+1];


        }
    }
    // Return the largest
    return max;
}

Reflect

I don’t believe there is an easier or faster way of implementing this. If you came up with a different solution leave it in the comments! I would love to see it!

Leave a comment