The challenge
Given an array of integers, Find the maximum product obtained from multiplying 2 adjacent numbers in the array.
Notes
- Array/list size is at least 2.
- Array/list numbers could be a mixture of positives, negatives also zeroes .
Input >Output Examples
adjacentElementsProduct([1, 2, 3]); ==> return 6
Explanation:
The maximum product is obtained from multiplying 2 * 3 = 6
, and they’re adjacent numbers in the array.
adjacentElementsProduct([9, 5, 10, 2, 24, -1, -48]); ==> return 50
Explanation:
Max product obtained from multiplying 5 * 10 = 50
.
adjacentElementsProduct([-23, 4, -5, 99, -27, 329, -2, 7, -921]) ==> return -14
Explanation:
The maximum product obtained from multiplying -2 * 7 = -14
, and they’re adjacent numbers in the array.
The solution in Python code
Option 1:
def adjacent_element_product(array):
return max( a*b for a, b in zip(array, array[1:]) )
Option 2:
def adjacent_element_product(arr):
product = [arr[i]*arr[i+1] for i in range(len(arr)-1)]
return max(product)
Option 3:
def adjacent_element_product(array):
max = array[0]*array[1];
for i in range(1,len(array)-1):
temp = array[i]*array[i+1]
if max < temp:
max = temp
return max
Test cases to validate our solution
import test
from solution import adjacent_element_product
@test.describe("Fixed Tests")
def fixed_tests():
@test.it("Positive numbers")
def _():
test.assert_equals(adjacent_element_product([5, 8]), 40)
test.assert_equals(adjacent_element_product([1, 2, 3]), 6)
test.assert_equals(adjacent_element_product([1, 5, 10, 9]), 90)
test.assert_equals(adjacent_element_product([4, 12, 3, 1, 5]), 48)
test.assert_equals(adjacent_element_product([5, 1, 2, 3, 1, 4]), 6)
@test.it("Both positive and negative values")
def _():
test.assert_equals(adjacent_element_product([3, 6, -2, -5, 7, 3]), 21)
test.assert_equals(adjacent_element_product([9, 5, 10, 2, 24, -1, -48]), 50)
test.assert_equals(adjacent_element_product([5, 6, -4, 2, 3, 2, -23]), 30)
test.assert_equals(adjacent_element_product([-23, 4, -5, 99, -27, 329, -2, 7, -921]), -14)
test.assert_equals(adjacent_element_product([5, 1, 2, 3, 1, 4]), 6)
@test.it("Contains zeroes")
def _():
test.assert_equals(adjacent_element_product([1, 0, 1, 0, 1000]), 0)
test.assert_equals(adjacent_element_product([1, 2, 3, 0]), 6)