Search code examples
c++algorithmvectorcoursera-api

Solving Maxium Pairwise Product using Sort Method


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


Solution

  • 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;
    }