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.
求三个数能让这三个数乘积最大,返回最大的乘积。想先排序。挑最大的三个数,计算这仨数的乘积,还要考虑,可能有两个负的。那就再考虑最大数和最小的两个数的乘积。就比较一下这两个乘积那个大,就选哪个。
class Solution {
public:
int maximumProduct(vector<int>& nums) {
sort(nums.begin(), nums.end());
int r1 = nums[nums.size() - 1] * nums[nums.size() - 2] * nums[nums.size() - 3];
int r2 = nums[0] * nums[1] * nums[nums.size() - 1];
if(r1 > r2)
return r1;
else
return r2;
}
};
网友评论