积器息
【题目描述】
给你一堆数,第 ii 个数表示为 a_ia i,请你计算 a i×a j的最大值(i不等于j) 。
【输入格式】
共两行。 第一行有一个数 nn,表示数的个数, 第二行有 nn 个数,第 ii 个数为 a_ia i
【输出格式】
见题意。
输入数据 1
5
1 2 3 4 5
输出数据 1
20
输入数据 2
3
0 2 4
输出数据 2
8
【数据范围】
对于100\%100%的数据,有:
n \leq 10^7n≤10 7-10^9 \leq a_i \leq 10^9−10 9≤a i ≤10 9
【提示】
注意数据范围
【以下回答由 GPT 生成】
首先,我们需要将输入的字符串解析为整数数组。可以使用stringstream来解析字符串,并将解析后的整数存入数组a中。
接下来,我们可以使用两层循环来遍历数组a,计算a[i]*a[j]的乘积,并找到最大的乘积。
最后,我们输出最大乘积。
下面是具体的代码实现:
#include <iostream>
#include <sstream>
#include <vector>
int getMaxProduct(const std::vector<int>& a) {
int maxProduct = INT_MIN;
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < a.size(); j++) {
if (i != j) {
int product = a[i] * a[j];
if (product > maxProduct) {
maxProduct = product;
}
}
}
}
return maxProduct;
}
int main() {
int n;
std::cin >> n;
std::cin.ignore();
std::string line;
std::getline(std::cin, line);
std::stringstream ss(line);
std::vector<int> a;
int num;
while (ss >> num) {
a.push_back(num);
}
int result = getMaxProduct(a);
std::cout << result << std::endl;
return 0;
}
这段代码将输入的整数数组解析为了一个vector,然后使用两层循环遍历数组,计算乘积,并找到最大的乘积。最后输出结果。
然而,上述代码的时间复杂度为O(n^2),在最坏情况下可能会超时。
为了提高效率,我们可以考虑只遍历一次数组,在遍历的过程中记录最大值和次大值。
具体实现可以参考下面的代码:
#include <iostream>
#include <sstream>
#include <vector>
long long int getMaxProduct(const std::vector<int>& a) {
long long int maxProduct = LLONG_MIN;
long long int maxNum = LLONG_MIN;
long long int secondMaxNum = LLONG_MIN;
for (int i = 0; i < a.size(); i++) {
if (a[i] > maxNum) {
secondMaxNum = maxNum;
maxNum = a[i];
} else if (a[i] > secondMaxNum) {
secondMaxNum = a[i];
}
long long int product = maxNum * secondMaxNum;
if (product > maxProduct) {
maxProduct = product;
}
}
return maxProduct;
}
int main() {
int n;
std::cin >> n;
std::cin.ignore();
std::string line;
std::getline(std::cin, line);
std::stringstream ss(line);
std::vector<int> a;
int num;
while (ss >> num) {
a.push_back(num);
}
long long int result = getMaxProduct(a);
std::cout << result << std::endl;
return 0;
}
这段代码只需要遍历一次数组,记录最大值和次大值,并计算乘积。最后输出结果。时间复杂度为O(n)。
希望这个答案能够帮到你。
【相关推荐】
把最大的两个数乘起来不就行