Maximum product of three elements in an array
Filed under Amazon
Free read 1 of 3Confirm that the array length is at least 3 and check how negative numbers affect the maximum product.
The question
Given an integer array, find three numbers whose product is maximum and return the maximum product.
Constraints
- 3 <= nums.length <= 10^4
- -1000 <= nums[i] <= 1000
Examples
- Input
- nums = [1, 2, 3]
- Output
- 6
- Why
- The product of all three elements is 6.
- Input
- nums = [-10, -10, 5, 2]
- Output
- 500
- Why
- The product of -10, -10, and 5 is 500.
Approach
Confirm that the array length is at least 3 and check how negative numbers affect the maximum product.
Check all possible triplets using three nested loops, resulting in O(N^3) time complexity.
Sort the array. The maximum product will be either the product of the three largest elements or the two smallest negative elements and the largest positive element.
Arrays with multiple negative values or containing zeros.
Solution
O(N log N) time, O(1) space
class Solution:
def maximumProduct(self, nums: list[int]) -> int:
nums.sort()
return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1])
Tips
- What they are testing: Test with arrays containing negative numbers, zeros, and all positive numbers.
- Common mistake: Assuming the maximum product is simply the product of the three largest numbers without considering two large negative numbers multiplying to a positive value.
Related Amazon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.