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.
(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。