题目描述
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) {
int n = nums.size();
vector<int> neg;
vector<int> pos;
for (int i=0; i<nums.size(); ++i) {
if (i < 0 || nums.empty()) break;
if (nums[i] < 0) {
neg.push_back(nums[i]);
}else {
pos.push_back(nums[i]);
}
}
sort(pos.begin(), pos.end());
sort(neg.begin(), neg.end());
int n1 = pos.size();
int n2 = neg.size();
int res = INT_MIN;
if (n1 >= 3)
res = max(res, pos[n1-1] * pos[n1-2] * pos[n1-3]);
if (n2 == n)
res = max(res, neg[n2-1] * neg[n2-2] * neg[n2-3]);
if (n2 >= 2 && n1 >= 1)
res = max(res, neg[0] * neg[1] * pos[n1-1]);
return res;
}
};