题目:给你一个整型数组 nums
,在数组中找出由三个数组成的最大乘积,并输出这个乘积。
示例 1:
输入:nums = [1,2,3]
输出:6
示例 2:
输入:nums = [1,2,3,4]
输出:24
示例 3:
输入:nums = [-1,-2,-3]
输出:-6
思路:1》数组全是负数或全是正数,都为最大的三个数乘积
2》剩下就是有正数有负数,结果可能为三个正数的乘积,也可能为两个最小负数和最大正数的乘积。
第一次写时把情况分的很细,代码如下:
class Solution {
public:
int maximumProduct(vector<int>& nums) {
sort(nums.begin(), nums.end());
int len = nums.size();
//cout << nums[0] << " " << nums[1] << " " << nums[2] << endl;
//cout << nums[len-3 ] << " " << nums[len - 2] << " " << nums[len - 1] << endl;
if (nums[1]>=0|| nums[len - 1] <=0)
{
return nums[len - 1] * nums[len - 2] * nums[len - 3];
}
else if (nums[len - 3] <= 0)
{
return nums[1] * nums[0] * nums[len - 1];
}
else
{
return ((nums[0] * nums[1]*nums[len - 1]) > (nums[len - 1] * nums[len - 2]* nums[len - 3]) ?
(nums[0] * nums[1] * nums[len - 1]) : (nums[len - 1] * nums[len - 2] * nums[len - 3]));
}
}
};
观察之后,就两种情况,要么为后三个数的乘积,要么为两个最小负数和最大正数的乘积。
改进后:
class Solution {
public:
int maximumProduct(vector<int>& nums) {
sort(nums.begin(), nums.end());
int len = nums.size();
return max(nums[0] * nums[1] * nums[len - 1], nums[len - 1] * nums[len - 2] * nums[len - 3]);
}
};
但这都用到了排序空间开销的会大点,因为最后结果就用到了最大的三个数和最小的三个数,可以线性遍历找出这五个数,取其中最大的三个数的乘积。
class Solution {
public:
int maximumProduct(vector<int>& nums) {
int len = nums.size();
int firstMax = INT_MIN, secondMax = INT_MIN, thirdMax = INT_MIN;
int firstMin = INT_MAX, secondMin = INT_MAX;
for (int i = 0; i < len; i++) {
if (nums[i] > firstMax) {
thirdMax = secondMax;
secondMax = firstMax;
firstMax = nums[i];
}
else if (nums[i] > secondMax) {
thirdMax = secondMax;
secondMax = nums[i];
}
else if (nums[i] > thirdMax) {
thirdMax = nums[i];
}
if (nums[i] >= firstMin&&nums[i]<secondMin) {
secondMin = nums[i];
}
else if (nums[i] < firstMin) {
secondMin = firstMin;
firstMin = nums[i];
}
}
return max(firstMax * secondMax * thirdMax, firstMax * firstMin * secondMin);
}
};