给定一个无序数组,包含正数、负数和0,要求从中找出3个数的乘积,使得乘积最大,要求时间复杂度:O(n),空间复杂度:O(1)
输入描述:
无序整数数组A[n]
输出描述:
满足条件的最大乘积
输入例子1:
3 4 1 2
输出例子1:
24
#include<vector>
#include<iostream>
#include<algorithm>
#include<set>
#include<string.h>
using namespace std;
int main()
{
int temp;
vector<int> A;
while (cin >> temp)
A.push_back(temp);
int max = 0x80000000, s_max = 0x80000000, t_max = 0x80000000, s_min = 0x3f3f3f3f, min = 0x3f3f3f3f;
for (int i = 0; i<A.size(); ++i) {
if (A[i]>max) max = A[i];
if (A[i]<min) min = A[i];
}
for (int i = 0; i<A.size(); ++i) {
if (A[i]>s_max&&A[i]<max) s_max = A[i];
}
for (int i = 0; i<A.size(); ++i) {
if (A[i]>t_max&&A[i]<s_max) t_max = A[i];
}
for (int i = 0; i<A.size(); ++i) {
if (A[i]>min&&A[i]<s_min) s_min = A[i];
}
if (max*s_max*t_max>max*s_min*min)
cout << max * s_max*t_max;
else
cout << max * s_min*min;
cout << endl;
return 0;
}