题目描述
给定一个无序数组,包含正数、负数和0,要求从中找出3个数的乘积,使得乘积最大,要求时间复杂度:O(n),空间复杂度:O(1)
输入描述:
无序整数数组A[n]
输出描述:
满足条件的最大乘积
long long b; b = 9338*9281*9313; //b值为-333598534
b = 9338*9281; b *= 9313; cout<<b<<endl; //b值为807120253114
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; int main() { long long b,b1; long long x,y,z; x = 9338; y = 9281; z = 9313; int x1,y1,z1; x1 = 9338; y1 = 9281; z1 = 9313; b = x*y*z; b1 = x1*y1*z1; cout<<b<<endl; //正确 cout<<b1<<endl; //结果错误 return 0; }
思路:最大乘积有3种情况,3个最大正数相乘,2个最大负数乘最大正数,0
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; long long a[10000001]; int main() { long long n; cin>>n; if(n<=2) return 0; for(int i=0;i<n;i++) { cin>>a[i]; } sort(a,a+n); long long maxn[3] = {-1,-1,-1}; maxn[0] = a[n-1]*a[n-2]; maxn[0] *= a[n-3]; //未分开乘导致出错 maxn[1] = 0; maxn[2] = a[0]*a[1]; maxn[2] *= a[n-1]; if(maxn[0]<maxn[1]) maxn[0] = maxn[1]; if(maxn[0]<maxn[2]) maxn[0] = maxn[2]; cout<<maxn[0]; return 0; }