要解决的问题:给定一个数组或数字序列,目标是找到通过该序列中一些 2 个数字相乘获得的最大数。
输入和输出示例
Input:
2
100000 90000
Correct output:
9000000000
Input:
3
1 2 3
Correct output:
6
我的解决方案:获取给定序列中的 2 个最大数字并将它们相乘我的代码有效,除非使用一种解决方案
我的代码
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void print(std::vector<int> const& input)
{
for (int i = 0; i < input.size(); i++) {
std::cout << input.at(i) << ' ';
}
}
int main()
{
vector<int> seq;
int n;
// Read the nb of elements in vect
cout << "please enter the number of elements in sequence"<<endl;
cin >> n;
// Read the vector
cout << "please enter the elements of the sequence"<<endl;
for (int i = 0; i < n; i++)
{
int input;
cin >> input;
seq.push_back(input);
}
cout << "sequence you entered" << endl;
print(seq);
// Find the 1st max element
double FisrtMax=*max_element(seq.begin(), seq.end());
cout <<endl<< "First Maximum Element is" << endl<< FisrtMax;
// remove the found element
std::vector<int>::iterator PosF = find(seq.begin(), seq.end(), FisrtMax);
seq.erase(PosF);
cout <<endl<< "sequence After removing the 1st maximum element" << endl;
print(seq);
// Find the 2nd max element
double SecMax = *max_element(seq.begin(), seq.end());
cout <<endl<< "Second Maximum Element is" << endl << SecMax;
//multiply the 2 elements
int total = (FisrtMax * SecMax);
cout <<endl<<"The Product of the 2 elemnts is "<< total;
return 0;
}
输入:
please enter the number of elements in sequence
2
please enter the elements of the sequence
1000000
90000
输出 :
please enter the number of elements in sequence
2
please enter the elements of the sequence
1000000
90000
sequence you entered
10000002105376900002105376
First Maximum Element is
1e+06
sequence After removing the 1st maximum element
900002105376
Second Maximum Element is
90000
The Product of the 2 elements is -2147483648