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
代码:
int maximumProduct(vector<int>& nums) { sort(nums.begin(),nums.end()); int len = nums.size(); int a,b,c; c = nums[len-1]; b = nums[len-2]; a = nums[len-3]; if(a>0)return max(nums[0]*nums[1]*c,a*b*c); else if( a ==0 ) { if(len==3)return 0; if(len>=5)return nums[len-5]*nums[len-4]*c;//l两个负数 else return a*b*c; } else if(a<0) { if(c<0 )return a*b*c; if(c>=0 &&b<0 )return nums[0]*nums[1]*c; if(c>=0 && b>0 &&len>=4)return nums[0]*nums[1]*c; if(c>=0 && b>0 &&len==3)return a*b*c; } return 0; } 首先排序,然后分别判断数组元素最大值是正是负的不同情况。