This is my code for the maximum pairwise product. It takes an array of numbers, sorts them to find the first and second maximum numbers, then return the product of them. The code works for small arrays and small values. But it fails with some numbers, and also it epically fails with large numbers such as 10000 and so.
i thought it was a problem with the data type i used, so i defined the data type to be int_64t so it can handle large numbers, but still i get the same wrong results! Can anyone help me with that?
#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
int64_t MaxPairwiseProduct(const std::vector<int64_t>& numbers) {
int n = numbers.size();
if(n<2)
return;
int maxind1=-1;
for (int i=0; i<=n; i++)
{
if(maxind1==-1 || numbers[i]>numbers[maxind1])
maxind1=i;
int maxind2=-1;
for (int j=0; j<=n; j++)
{
if(maxind1!=j && maxind2==-1 || numbers[j]>numbers[maxind2])
maxind2=j;}
int64_t restult=numbers[maxind1]*numbers[maxind2];
return restult;
}
int main() {
int n;
std::cin >> n;
std::vector<int64_t> numbers(n);
for (int i = 0; i < n; ++i) {
std::cin >> numbers[i];
}
cout << MaxPairwiseProduct(numbers) << "\n";
return 0;
}