Problem
You are given an integer arraynums.
Find three numbers whose product is maximum and return the maximum product.
Examples
Constraints
3 <= nums.length <= 10^4-1000 <= nums[i] <= 1000
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 628 with 16 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 628 # by problem number
lcpy gen -s maximum_product_of_three_numbers # by problem name
nums.
Find three numbers whose product is maximum and return the maximum product.
Input: nums = [1,2,3]
Output: 6
Explanation: The only three numbers are 1, 2, and 3, so the maximum product is 1 * 2 * 3 = 6.
Input: nums = [1,2,3,4]
Output: 24
Explanation: The largest product comes from the three greatest numbers: 2 * 3 * 4 = 24.
Input: nums = [-1,-2,-3]
Output: -6
Explanation: The only three numbers are -1, -2, and -3, so the maximum product is (-1) * (-2) * (-3) = -6.
3 <= nums.length <= 10^4-1000 <= nums[i] <= 1000class Solution:
# Time: O(n)
# Space: O(1)
def maximum_product(self, nums: list[int]) -> int:
max1 = max2 = max3 = -(10**18)
min1 = min2 = 10**18
for num in nums:
if num > max1:
max1, max2, max3 = num, max1, max2
elif num > max2:
max2, max3 = num, max2
elif num > max3:
max3 = num
if num < min1:
min1, min2 = num, min1
elif num < min2:
min2 = num
return max(max1 * max2 * max3, max1 * min1 * min2)
| Time | Space |
|---|---|
| O(n) | O(1) |