Find a pair with maximum product in array of Integers in C++

C++Server Side ProgrammingProgramming

Consider we have an array A, there are n different elements. We have to find a pair (x, y) from the array A, such that the product of x and y is maximum. The array may contain positive or negative elements. Suppose an array is like: A = [-1, -4, -3, 0, 2, -5], then the pair will be (-4, -5) as product is maximum.

To solve this problem, we have to keep track four numbers, the positive_max, positive_second_max, negative_max, negative_second_max. At the end if the (positive_max * positive_second_max) is greater than (negative_max * negative_second_max), then return positive pairs, otherwise return negative pairs.

Example

#include<iostream>
#include<cmath>
using namespace std;
void maxProdPair(int arr[], int n) {
   if (n < 2) {
      cout << "No pair is present";
      return;
   }
   if (n == 2) {
      cout << "(" << arr[0] << ", " << arr[1] << ")" << endl;
      return;
   }
   int pos_max = INT_MIN, pos_second_max = INT_MIN;
   int neg_max = INT_MIN, neg_second_max = INT_MIN;
   for (int i = 0; i < n; i++) {
      if (arr[i] > pos_max) {
         pos_second_max = pos_max;
         pos_max = arr[i];
      } else if (arr[i] > pos_second_max)
      pos_second_max = arr[i];
      if (arr[i] < 0 && abs(arr[i]) > abs(neg_max)) {
         neg_second_max = neg_max;
         neg_max = arr[i];
      }
      else if(arr[i] < 0 && abs(arr[i]) > abs(neg_second_max))
      neg_second_max = arr[i];
   }
   if (neg_max*neg_second_max > pos_max*pos_second_max)
      cout << "(" << neg_max << ", " << neg_second_max << ")" << endl;
   else
      cout << "(" << pos_max << ", " << pos_second_max << ")" << endl;
}
int main() {
   int arr[] = {-1, -4, -3, 0, 2, -5};
   int n = sizeof(arr)/sizeof(arr[0]);
   maxProdPair(arr, n);
}

Output

(-5, -4)
raja
Published on 24-Oct-2019 12:50:20
Advertisements