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.
思路:最大值可能是3个正数相乘或者1正两个最小的负数相乘。
class Solution {
public:
int maximumProduct(vector<int>& nums) {
int pMax, psMax, ptMax;
pMax = psMax = ptMax = INT_MIN;
int nMin, nsMin;
nMin = nsMin = INT_MAX;
for(int i = 0; i < nums.size(); i++){
int t = nums[i];
if(t > pMax) {
ptMax = psMax;
psMax = pMax;
pMax = t;
} else if(t > psMax) {
ptMax = psMax;
psMax = t;
} else if(t > ptMax)
ptMax = t;
if(t < nMin){
nsMin = nMin;
nMin = t;
} else if(t < nsMin)
nsMin = t;
}
return max(pMax * psMax * ptMax, pMax * nMin * nsMin);
}
};