[Array]628. Maximum Product of Three Numbers

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:

  1. The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
  2. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.

思路:给出一个数组找出里面三个元素乘积的最大值并输出。先对整个数组进行排序,考虑到有负数的情况,因此,三个数的乘积有两种情况,2负1正,或者3个正数,如果只三个数便直接输出。

自己代码:

 int maximumProduct(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
if(nums[] < && nums[] < && nums[]*nums[]*nums[n-] > nums[n-]*nums[n-]*nums[n-])
return nums[]*nums[]*nums[n-];
else
return nums[n-] * nums[n-] * nums[n-];
}

优秀代码:

 int maximumProduct(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
int m1 = nums[]*nums[]*nums[n-];
int m2 = nums[n-] * nums[n-] * nums[n-];
return m1 > m2?m1:m2; //或者 return max(m1, m2);
}

其实不用检验前面两个元素是否是负数,因为只有两种情况,前面两个,后面一个,或者后面三个。

上一篇:ZOJ4060 Flippy Sequence(思维题)


下一篇:[LeetCode] 628. Maximum Product of Three Numbers_Easy