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.
The solution involves two main possibilities for the maximum product:
To efficiently compute these values, we can sort the array. Once sorted:
nums[-1], nums[-2], nums[-3]).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.
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)
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).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:
nums = [1,2,3] → Output: 6 (option1: 1*2*3=6, option2: 1*2*3=6 → max is 6).nums = [-10,-9,1,2,3] → Output: 270 (option1: 1*2*3=6, option2: -10*-9*3=270 → max is 270).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.
(免責聲明:本文為本網(wǎng)站出于傳播商業(yè)信息之目的進行轉(zhuǎn)載發(fā)布,不代表本網(wǎng)站的觀點及立場。本文所涉文、圖、音視頻等資料的一切權(quán)利和法律責任歸材料提供方所有和承擔。本網(wǎng)站對此資訊文字、圖片等所有信息的真實性不作任何保證或承諾,亦不構(gòu)成任何購買、投資等建議,據(jù)此操作者風險自擔。) 本文為轉(zhuǎn)載內(nèi)容,授權(quán)事宜請聯(lián)系原著作權(quán)人,如有侵權(quán),請聯(lián)系本網(wǎng)進行刪除。