题目
链接:https://www.nowcoder.com/questionTerminal/5f29c72b1ae14d92b9c3fa03a037ac5f
来源:牛客网
[编程题]最大乘积
热度指数:17812时间限制:1秒空间限制:32768K
给定一个无序数组,包含正数、负数和0,要求从中找出3个数的乘积,使得乘积最大,要求时间复杂度:O(n),空间复杂度:O(1)
输入描述:
无序整数数组A[n]
输出描述:
满足条件的最大乘积
示例1
输入
3 4 1 2
输出
24
解法
代码
#include<iostream>
#include<stdlib.h>
#include<iomanip>
#include<math.h>
#include<algorithm>
#include<vector>
#include<functional>
#include<string>
#include<climits>
#include <cstdlib>
using namespace std;
int main()
{
const int MAX_INT = 0x7fffffff;
const int MIN_INT = 0x80000000;
long max[3] = { MIN_INT };
long min[2] = { MAX_INT };
int num,n;
int count = 0;
long long result = 1;
//int nums[] = { 3472, -7098, -9281, 7789, 7955, 6101, 5051, 7778, 3090, 7423, -7151, 5652, 1595, -8094, 677, -8324, 8347, -2482, 9313, -9338, -3157, 8559, 6945, 3618, 3087, 121, -8468, 3225, 1356, 6939, 2799, -7231, -6309, -5453, 633, -8689, -4776, 2714, -2743, -1409, 5918, -3333, 1803, 8330, -2206, -6117, -4486, -7903, -4375, -3739, 2897, 8056, -5864, -522, 7451, -4541, -2813, 5790, -532, -6517, 925 };
cin>>n;
while(count<n)
{
cin>>num;
if (max[0] < num)
{
max[0] = num;
for (int i = 1; i < 3; i++)
{
if (max[i] < num)
{
max[i - 1] = max[i];
max[i] = num;
}
else
break;
}
}
if (min[0] > num)
{
min[0] = num;
if (min[1] > num)
{
min[0] = min[1];
min[1] = num;
}
}
//cout <<"maxs: " <<max[0] << " " << max[1] << " " << max[2] <<" mins: "<< min[0] << " " << min[1] << endl;
if (count < 3)
{
result *= num;
}
else
{
if (max[0] * max[1] * max[2] >= max[2] * min[0] * min[1])
result = max[0] * max[1] * max[2];
else
result = max[2] * min[0] * min[1];
}
count++;
}
cout << result << endl;
system("pause");
return 0;
}