题目:
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.
代码:
#include<algorithm>
class Solution {
public:
int maximumProduct(vector<int>& nums) {
sort(nums.begin(), nums.end());
int max1 = nums[0] * nums[1] * nums[nums.size()-1];
int max2 = nums[nums.size()-3] * nums[nums.size()-2] * nums[nums.size()-1];
return max(max1, max2);
}
};
代码2:
class Solution {
public:
int maximumProduct(vector<int>& nums) {
/* int size=nums.size();
sort(nums.begin(),nums.end());
int x=nums[0]*nums[1];
int y=nums[size-2]*nums[size-3];
if(x>y)
{
return nums[size-1]*x;
}
else
{
return nums[size-1]*y;
}
}
int n = nums.size();
partial_sort(nums.begin(), nums.begin()+3, nums.end(), greater<int>());
int c1 = nums[0], c2 = nums[1],c3 = nums[2];
partial_sort(nums.begin(), nums.begin()+2, nums.end());
int d1 = nums[0], d2 = nums[1];
return max(c1*c2*c3, d1*d2*c1);*/
if (nums.size() == 3) return nums[0] * nums[1] * nums[2];
int a[5] = {-1001,-1001,-1001,1001,1001};
int i;
for (i = 0; i < nums.size(); i++)
{
if ((nums[i]>a[0])) a[0] = nums[i];
if (a[0] > a[1]) swap(a[0], a[1]);
if (a[1] > a[2]) swap(a[1], a[2]);
if ((nums[i] < a[3])) a[3] = nums[i];
if (a[3] < a[4]) swap(a[3], a[4]);
}
return max(a[0]*a[1]*a[2],a[2]*a[3]*a[4]);
}
};