This website contains ALL LeetCode **Premium** problems for
**FREE!!**.

All leaked interview problems are collected from Internet.

All leaked interview problems are collected from Internet.

Given an integer array, find three numbers whose product is maximum and output the maximum product.

**Example 1:**

Input:[1,2,3]Output:6

**Example 2:**

Input:[1,2,3,4]Output:24

**Note:**

- The length of the given array will be in range [3,10
^{4}] and all elements are in the range [-1000, 1000]. - Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.

b'

\n## Solution

\n

\n#### Approach #1 Brute Force [Time Limit Exceeded]

\n

\n#### Approach #2 Using Sorting [Accepted]

\n

\n#### Approach #3 Single Scan [Accepted]

\n

\n

'
\n\n

\n\n

The simplest solution is to consider every triplet out of the given array and check their product and find out the maximum product out of them.

\n**Complexity Analysis**

- \n
- \n
Time complexity : . We need to consider every triplet from array of length .

\n \n - \n
Space complexity : . Constant extra space is used.

\n \n

\n

**Algorithm**

Another solution could be to sort the given array(in ascending order) and find out the product of the last three numbers.

\nBut, we can note that this product will be maximum only if all the numbers in array are positive. But, in the given problem statement, negative elements could exist as well.

\nThus, it could also be possible that two negative numbers lying at the left extreme end could also contribute to lead to a larger product if the third number in the triplet being considered is the largest positive number in the array.

\nThus, either the product xx or xx will give the required result. Thus, we need to find the larger one from out of these values.

\n\n**Complexity Analysis**

- \n
- \n
Time complexity : . Sorting the array takes time.

\n \n - \n
Space complexity : . Sorting takes O(logn) space.

\n \n

\n

**Algorithm**

We need not necessarily sort the given array to find the maximum product. Instead, we can only find the required 2 smallest values( and ) and the three largest values() in the array, by iterating over the array only once.

\nAt the end, again we can find out the larger value out of xx and xx to find the required maximum product.

\n\n**Complexity Analysis**

- \n
- \n
Time complexity : . Only one iteration over the array of length is required.

\n \n - \n
Space complexity : . Constant extra space is used.

\n \n

\n

Analysis written by: @vinod23

\n