内容中心

2026年专业靠谱口碑好的航空充气密封圈生产厂家帮我推荐几家

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

  1. 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).
  2. 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).
  3. 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:

  1. 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 is 2*3=6, and the product of the two smallest elements is 1*2=2. The maximum is 6.
  2. 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 is 1*2=2, and the product of the two smallest elements is (-5)*(-4)=20. The maximum is 20.
  3. 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 is 2.

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.



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?