Skip to content
On this page

Adjacent Elements Product

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

An array of integers containing at least two elements.

Guaranteed constraints:

  • 2 ≤ inputArray.length ≤ 10,
  • -1000 ≤ inputArray[i] ≤ 1000

Output

The largest product of adjacent elements.

Solution

Solution 1
rust
fn solution(inputArray: Vec<i32>) -> i32 {
    inputArray.windows(2).map(|x| x.iter().product() ).max().unwrap()
}
Solution 2
rust
fn solution(inputArray: Vec<i32>) -> i32 {
    let mut largest_product = i32::MIN;
    for second in 1..inputArray.len() {
        let product = inputArray[second-1]*inputArray[second];
        if product > largest_product {
            largest_product = product;
        }
    }

    largest_product
}