628 Maximum Product of Three Numbers 三個數(shù)的最大乘積
Description:
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example:
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,10^4] 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.
題目描述:
給定一個整型數(shù)組,在數(shù)組中找出由三個數(shù)組成的最大乘積园蝠,并輸出這個乘積型宝。
示例 :
示例 1:
輸入: [1,2,3]
輸出: 6
示例 2:
輸入: [1,2,3,4]
輸出: 24
注意:
給定的整型數(shù)組長度范圍是[3,10^4]住涉,數(shù)組中所有的元素范圍是[-1000, 1000]。
輸入的數(shù)組中任意三個數(shù)的乘積不會超出32位有符號整數(shù)的范圍碎捺。
思路:
有兩種情況需要考慮, 如果有 3個以上的正數(shù), 則最大乘積為3個最大的正數(shù)的乘積; 或者最大乘積是兩個絕對值最大的負數(shù)和最大的正數(shù)的乘積
- 遍歷列表, 參考LeetCode #414 Third Maximum Number 第三大的數(shù)
時間復(fù)雜度O(n), 空間復(fù)雜度O(1) - 對列表進行排序, 選擇最后三個數(shù)或者最后一個數(shù)和開頭兩個數(shù)的最大乘積即可
時間復(fù)雜度O(nlgn), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
int maximumProduct(vector<int>& nums)
{
int max1 = -1000, max2 = -1000, max3 = -1000, min1 = 1000, min2 = 1000;
for (auto num : nums)
{
if (num > max1)
{
max3 = max2;
max2 = max1;
max1 = num;
}
else if (num > max2)
{
max3 = max2;
max2 = num;
}
else if (num > max3) max3 = num;
if (num < min1)
{
min2 = min1;
min1 = num;
}
else if (num < min2) min2 = num;
}
return max(max1 * max2 * max3, min1 * min2 * max1);
}
};
Java:
class Solution {
public int maximumProduct(int[] nums) {
int max1 = -1000, max2 = -1000, max3 = -1000, min1 = 1000, min2 = 1000;
for (int num : nums) {
if (num > max1) {
max3 = max2;
max2 = max1;
max1 = num;
} else if (num > max2) {
max3 = max2;
max2 = num;
} else if (num > max3) max3 = num;
if (num < min1) {
min2 = min1;
min1 = num;
} else if (num < min2) min2 = num;
}
return Math.max(max1 * max2 * max3, min1 * min2 * max1);
}
}
Python:
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums.sort()
return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-1])