To solve this problem, we need to find the maximum product of any two distinct elements in a given list of integers. The key insight here is that the maximum product can either come from the product of the two largest elements (which are positive) or the product of the two smallest elements (which could be negative, leading to a positive product when multiplied together).
Approach
- Sort the List: First, we sort the list in non-decreasing order. This allows us to easily access the two smallest elements (at the start of the list) and the two largest elements (at the end of the list).
- Calculate Products: Compute two products:
- The product of the two largest elements (last two elements in the sorted list).
- The product of the two smallest elements (first two elements in the sorted list).
- Return Maximum: The maximum of these two products will be our answer, as it covers all possible cases (positive-positive, negative-negative, mixed positive-negative).
Solution Code
def getMaxProduct(nums):
nums_sorted = sorted(nums)
product_largest = nums_sorted[-1] * nums_sorted[-2]
product_smallest = nums_sorted[0] * nums_sorted[1]
return max(product_largest, product_smallest)
Explanation
Let’s break down the approach using examples:
- Case 1 (Positive Elements Only): For the list
[1,2,3], the sorted list is[1,2,3]. The product of the two largest elements is2*3=6, and the product of the two smallest elements is1*2=2. The maximum is6. - Case 2 (Negative Elements): For the list
[-5,-4,1,2], the sorted list is[-5,-4,1,2]. The product of the two largest elements is1*2=2, and the product of the two smallest elements is(-5)*(-4)=20. The maximum is20. - Case 3 (Mixed Positive and Negative Elements): For the list
[5,-1,-2], the sorted list is[-2,-1,5]. The product of the two largest elements is(-1)*5=-5, and the product of the two smallest elements is(-2)*(-1)=2. The maximum is2.
This approach efficiently handles all possible scenarios and runs in O(n log n) time complexity due to sorting, which is optimal for most practical purposes. For very large lists, an O(n) approach (tracking the two largest and two smallest elements in one pass) can be used, but the sorted approach is simpler and easier to implement.
Answer: The function getMaxProduct as defined above.
作者声明:本文包含人工智能生成内容。