Topic:
Given an integer array, find the largest product consisting of three numbers in the array, and output this product.
Example_1:
Input: [1,2,3]
Output: 6
Example_2:
Input: [1,2,3,4]
Output: 24
Solution_1 (multiple traversal):
Continuously sample and arrange the numbers in the array, and
return directly after judging the largest value. The
operation efficiency is extremely low. It is not recommended
Code_1:
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
n = len(nums)
return max(nums[i] * nums[j] * nums[b]
for i in range(n) for j in range(i + 1, n) for b in range(j + 1, n))
Solution_2 (greedy):
First, sort the array.
For all negative numbers and all positive numbers:
just return the product of the largest three numbers
For the case of both positive and complex numbers in the array:
if there are more than three positive numbers, then the product of the three positive numbers may be the largest.
If there are at least two negative numbers, then the smallest two negative numbers will be multiplied to get one Larger positive number,
then the product of this positive number and the largest positive number may also be the largest
Code_2:
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums.sort()
return max(nums[-1] * nums[-2] * nums[-3], nums[-1] * nums[0] * nums[1])
Solution_3 (Linear Scan):
After understanding the second solution method, optimize the second one.
First find out the numbers in the first three digits and arrange them as max_1, max_2, max_3 and
then find the numbers in the first two digits from large to small. Find out min_2, min_1
Then it is judged during the traversal process, and
the value is continuously updated.
Finally, the maximum value in the second method is also output.
Code_3:
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
max_1, max_2, max_3 = sorted([nums[0], nums[1], nums[2]])
min_2, min_1 = sorted([nums[0], nums[1]])
for i in nums:
if i > max_1:
max_3 = max_2
max_2 = max_1
max_1 = i
elif i <= max_1 and i >= max_2:
max_3 = max_2
max_2 = i
elif i <= max_2 and i >= max_3:
max_3 = i
if i <= min_1:
min_2 = min_1
min_1 = i
elif i >= min_1 and i <= min_2:
min_2 = i
return max(min_1 * min_2 * max_1, max_1 * max_2 * max_3)
Result: