[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个正数,如果只三个数便直接输出。

自己代码:

1 int maximumProduct(vector<int>& nums) {
2         sort(nums.begin(), nums.end());
3         int n = nums.size();
4         if(nums[0] < 0 && nums[1] < 0 && nums[0]*nums[1]*nums[n-1] > nums[n-1]*nums[n-2]*nums[n-3])
5                 return nums[0]*nums[1]*nums[n-1];
6         else 
7            return nums[n-1] * nums[n-2] * nums[n-3]; 
8     }

优秀代码:

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

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

posted @ 2017-08-11 15:00  两猿社  阅读(191)  评论(0编辑  收藏  举报