-2

I am trying to solve the maximum pairwise product problem by first sorting the vector and then multiplying the last two elements of the vector.

It works fine for the smaller digits but not for the 10^5 digits.

Can anyone please look it out and help?

this is my function

long long MaxPairwiseProductFast(const vector<int> &number)
{
    long long result = 0;
    long n = number.size();
    result = number.at(n-1) * number.at(n-2);
    return result;
}

and this is my main function

int main()
{
    int n;
    cin>>n;
    vector<int>numbers(n);
    for(int i = 0; i <n; i++){
     cin>>numbers[i];
    }
   sort(numbers.begin(), numbers.end());

    long long result = MaxPairwiseProductFast(numbers);

    cout<<result<<"\n";

    return 0;
}

it works fine for smaller range, but not for the bigger range even after using long long

  • 1
    When you say it doesn't work, what goes wrong? Do you have an example that fails? I guess this is an online judge? Do you need to remember all of the numbers? Do you need to sort them all? You only really need the largest two. – Rup May 02 '19 at 09:34
  • Have YOU tried debugging? – MrSmith42 May 02 '19 at 10:00

2 Answers2

1

First thing you need to change data type of vector from int to long long everywhere you have written vector<int>number to vector<long long>number.

Another change you need to do to get correct output is , you have to think for a case where there are more at least two bigger negative numbers.

For example: if vector contains : {-10, -5, -2, 0, 1, 2}.
Your program will output: 1 * 2 = 2 as an answer.
But, answer for this case will be: -10 * -5 = 50.

So, corrected calculation method will be:

long long MaxPairwiseProductFast(const vector<long long> &number)
{
  long long result = 0;
  long n = number.size();
  if (n < 2) return 0;
  result = number.at(n-1) * number.at(n-2);
  result = max(result, number.at(0) * number.at(1));
  return result;
}
BishalG
  • 1,414
  • 13
  • 24
1

You don't need to change all your data types as other answers suggest. Just fix your multiply like this:

long long MaxPairwiseProductFast(const vector<int> &number)
{
    long long result = 0;
    long n = number.size();
    result = number.at(n-1) * (long long)number.at(n-2);
    return result;
}

The problem is that you are multiplying two int * int, which produces an int, and then returning it as a long long. You need to cast one of them before multiplying so it will do a long long multiplication with a long long result.

Also check the product of the smallest two numbers, as Bishal suggests, since -5 * -5 > 4 * 4

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87