内容中心

2026年质量好的成都集装箱定制/成都集装箱厕所可靠供应商参考推荐几家

To solve this problem, we need to find the maximum product of three numbers in an integer array. The key insight here is to consider both positive and negative numbers, as the product of two large negative numbers and one large positive number can sometimes be larger than the product of the three largest positive numbers.

Approach

The solution involves two main possibilities for the maximum product:

  1. Product of the three largest elements: This is the case when all three numbers are positive or the negative numbers are not large enough to contribute to a larger product.
  2. Product of the two smallest elements (most negative) and the largest element: This is the case when the product of the two most negative numbers (which is positive) multiplied by the largest positive number gives a larger product than the three largest elements.

To efficiently compute these values, we can sort the array. Once sorted:

  • The three largest elements are at the end of the array (nums[-1], nums[-2], nums[-3]).
  • The two smallest elements are at the beginning of the array (nums[0], nums[1]), and the largest element is at the end (nums[-1]).

The maximum product is the maximum of these two possible products.

Solution Code

def maximumProduct(nums):
    nums_sorted = sorted(nums)
    option1 = nums_sorted[-1] * nums_sorted[-2] * nums_sorted[-3]
    option2 = nums_sorted[0] * nums_sorted[1] * nums_sorted[-1]
    return max(option1, option2)

Explanation

  1. Sorting: The array is sorted to easily access the largest and smallest elements.
  2. Option Calculation:
    • option1: Product of the three largest elements (last three elements in the sorted array).
    • option2: Product of the two smallest elements (first two elements) and the largest element (last element).
  3. Result: The maximum value between option1 and option2 gives the desired result.

This approach handles all edge cases, including arrays with all positive numbers, all negative numbers, and a mix of positive and negative numbers. The time complexity is dominated by the sorting step, which is (O(n \log n)), where (n) is the length of the array. This is efficient enough for most practical purposes.

Example Test Cases:

  • Test Case 1: nums = [1,2,3] → Output: 6 (option1: 1*2*3=6, option2: 1*2*3=6 → max is 6).
  • Test Case 2: nums = [-10,-9,1,2,3] → Output: 270 (option1: 1*2*3=6, option2: -10*-9*3=270 → max is 270).
  • Test Case3: nums = [-4,-3,-2,-1] → Output: -6 (option1: -3*-2*-1=-6, option2: -4*-3*-1=-12 → max is -6).

This solution correctly handles all these cases and provides the optimal result.



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

在线客服

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