[编程题] 最大乘积
时间限制:1秒
空间限制:32768K
给定一个无序数组,包含正数、负数和0,要求从中找出3个数的乘积,使得乘积最大,要求时间复杂度:O(n),空间复杂度:O(1)
输入描述:
无序整数数组A[n]
输出描述:
满足条件的最大乘积
输入例子1:
3 4 1 2
输出例子1:
24
Point:The result is the product of maximum three or the product of minimum two and maximum one.
#include<iostream>
#include<algorithm>
#include<stdlib.h>
using namespace std;
long ma1,ma2,ma3;
long mi1,mi2;
void selection(long A[],long n)
{
ma1=ma2=ma3=mi1=mi2=A[0];
long temp;
for(int i=1;i<n;i++)
{
if(A[i]>ma3){
if(A[i]>ma1){
temp=ma1;ma1=A[i];
ma3=ma2;ma2=temp;
}
else if(A[i]>ma2){ temp=ma2;ma2=A[i];ma3=temp;}
else { ma3=A[i];}
}
if(A[i]<mi2){
if(A[i]<mi1){
temp=mi1;mi1=A[i]; mi2=temp;
}
else { mi2=A[i];}
}
}
}
int main()
{
long n;
cin>>n;
long *A=new long[n];
for(long i=0;i<n;i++)cin>>*(A+i);
selection(A,n);
if(n==3)cout<<A[0]*A[1]*A[2]<<endl;
else cout<<max(ma1*mi1*mi2,ma1*ma2*ma3)<<endl;
return 0;
}