DEV Community

kingsley okpara
kingsley okpara

Posted on

Algorithm 101: The max product of three numbers in an array

This question appears in Codility.com, it is about finding the maximum product from three numbers in an array of integers.
Below is the full question
codility question
This is my simple solution in python

def solution(A):
    # write your code in Python 3.6
    A.sort()
    if A[-1] < 0:
        prod = (A[-1] * A[-2] * A[-3])
    elif A[0] * A[1] > A[-2] * A[-3]:
        prod = (A[-1] * A[1] * A[0])       
    else:
        prod = (A[-1] * A[-2] * A[-3])
    return prod

This is my explanation
First of all, I sort the array to have the elements in an ascending order
secondly, if the last element in the array is less than 0, that means all the elements in the array are negative, therefore, the maximum product will be the product of the last three elements
thirdly, I consider the situation where the product of two negative is greater than the product of the second to the last and third to the last (remember in mathematics that - * - = +)
lastly, if all the other conditions are not satisfied, therefore the maximum product will be the product of the last three elements

Top comments (0)