Given an integer array nums
, find three numbers whose product is maximum and return the maximum product.
For example:
nums = [1, 2, 3]
, the output should be 6.nums = [1, 2, 3, 4]
, the output should be 24.nums = [-1, -2, -3]
, the output should be -6.Explain an efficient algorithm to solve this problem, analyze its time and space complexity, and discuss potential edge cases and how to handle them. Assume the array has at least 3 elements and each element is between -1000 and 1000.
## Maximum Product of Three Numbers
### Problem Description
Given an integer array `nums`, the task is to find three numbers whose product is maximum and return the maximum product.
**Example 1:**
Input: nums = [1,2,3] Output: 6
**Example 2:**
Input: nums = [1,2,3,4] Output: 24
**Example 3:**
Input: nums = [-1,-2,-3] Output: -6
### Naive Solution
A straightforward approach would be to generate all possible combinations of three numbers from the array, calculate their product, and then find the maximum among these products. This involves three nested loops, resulting in a time complexity of O(n^3).
```python
import sys
def maximum_product_naive(nums):
n = len(nums)
if n < 3:
return None # Or raise an exception
max_product = -sys.maxsize - 1
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
product = nums[i] * nums[j] * nums[k]
max_product = max(max_product, product)
return max_product
A more efficient approach is to sort the array and then consider two cases:
The maximum of these two products will be the answer. This method has a time complexity of O(n log n) due to the sorting step.
def maximum_product(nums):
nums.sort()
n = len(nums)
return max(nums[n-1] * nums[n-2] * nums[n-3], nums[0] * nums[1] * nums[n-1])
The optimal solution involves sorting the array, which typically uses an algorithm like quicksort or mergesort with an average time complexity of O(n log n). After sorting, we perform a constant number of multiplications and comparisons, which take O(1) time.
Therefore, the overall time complexity is dominated by the sorting step, making it O(n log n).
The space complexity depends on the sorting algorithm used.
In the provided Python code, nums.sort()
is generally implemented using Timsort, which has a space complexity that can range from O(1) to O(n) depending on the input array's characteristics. For simplicity, we can assume O(log n) space complexity in most practical scenarios.
Array with fewer than three elements:
None
).Array with all positive numbers:
Array with all negative numbers:
Array with a mix of positive and negative numbers:
Zeroes in the array:
Here's how the optimal solution handles these cases:
def maximum_product_with_edge_cases(nums):
n = len(nums)
if n < 3:
raise ValueError("Array must have at least three elements")
nums.sort()
return max(nums[n-1] * nums[n-2] * nums[n-3], nums[0] * nums[1] * nums[n-1])