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.
思路:
首先排序,然后分别判断数组元素最大值是正是负情况。
int maximumProduct(vector<int>& nums)
{ sort(nums.begin(),nums.end());
int len = nums.size(); int a,b,c;
c = nums[len-];
b = nums[len-];
a = nums[len-];
if(a>)return max(nums[]*nums[]*c,a*b*c);
else if( a == )
{
if(len==)return ;
if(len>=)return nums[len-]*nums[len-]*c;//l两个负数
else return a*b*c;
}
else if(a<)
{
if(c< )return a*b*c;
if(c>= &&b< )return nums[]*nums[]*c;
if(c>= && b> &&len>=)return nums[]*nums[]*c;
if(c>= && b> &&len==)return a*b*c;
} return ;
}
感觉写出来 超级啰嗦 惨不忍睹,于是看到了如下代码,
醍醐灌顶,五体投地。 排序过后,依次讨论前三个,后三个,以及后两个跟第一个,前两个跟最后一个。
public int maximumProduct(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
int s = nums[n-] * nums[n-] * nums[n-];
s = Math.max(s, nums[n-] * nums[n-] * nums[]);
s = Math.max(s, nums[n-] * nums[] * nums[]);
s = Math.max(s, nums[] * nums[] * nums[]);
return s;
}