[LeetCode] 628. Maximum Product of Three Numbers 三个数字的最大乘积
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3] Output: 6
Example 2:
Input: [1,2,3,4] Output: 24
Note:
- The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
- Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.
给一个整数数组,找出乘积最大的3个数,返回这3个数组。
解法:这题的难点主要是要考虑到负数和0的情况。最大乘积可能是最大的3个正数相乘或者是最小的2个负数和最大的1个正数相乘。
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public int maximumProduct( int [] nums) { int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE, min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; for ( int n : nums) { if (n > max1) { max3 = max2; max2 = max1; max1 = n; } else if (n > max2) { max3 = max2; max2 = n; } else if (n > max3) { max3 = n; } if (n < min1) { min2 = min1; min1 = n; } else if (n < min2) { min2 = n; } } return Math.max(max1*max2*max3, max1*min1*min2); } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | # Time: O(n) # Space: O(1) class Solution( object ): def maximumProduct( self , nums): """ :type nums: List[int] :rtype: int """ min1, min2 = float ( "inf" ), float ( "inf" ) max1, max2, max3 = float ( "-inf" ), float ( "-inf" ), float ( "-inf" ) for n in nums: if n < = min1: min2 = min1 min1 = n elif n < = min2: min2 = n if n > = max1: max3 = max2 max2 = max1 max1 = n elif n > = max2: max3 = max2 max2 = n elif n > = max3: max3 = n return max (min1 * min2 * max1, max1 * max2 * max3) |
Python:
1 2 3 | def maximumProduct( self , nums): nums.sort() return max (nums[ - 1 ] * nums[ - 2 ] * nums[ - 3 ], nums[ 0 ] * nums[ 1 ] * nums[ - 1 ]) |
Python:
1 2 3 | def maximumProduct( self , nums): a, b = heapq.nlargest( 3 , nums), heapq.nsmallest( 2 , nums) return max (a[ 0 ] * a[ 1 ] * a[ 2 ], b[ 0 ] * b[ 1 ] * a[ 0 ]) |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Solution { public : int maximumProduct(vector< int >& nums) { int mx1 = INT_MIN, mx2 = INT_MIN, mx3 = INT_MIN; int mn1 = INT_MAX, mn2 = INT_MAX; for ( int num : nums) { if (num > mx1) { mx3 = mx2; mx2 = mx1; mx1 = num; } else if (num > mx2) { mx3 = mx2; mx2 = num; } else if (num > mx3) { mx3 = num; } if (num < mn1) { mn2 = mn1; mn1 = num; } else if (num < mn2) { mn2 = num; } } return max(mx1 * mx2 * mx3, mx1 * mn1 * mn2); } }; |
类似题目:
[LeetCode] 152. Maximum Product Subarray 求最大子数组乘积
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步