在C ++中以整数数组查找最大乘积对

考虑我们有一个数组A,有n个不同的元素。我们必须从数组A中找到一个对(x,y),以使x和y的乘积最大。该数组可以包含正或负元素。假设一个数组像:A = [-1,-4,-3,0,2,-5],则该对将为(-4,-5),因为乘积最大。

为了解决这个问题,我们必须跟踪四个数字,即positive_max,positive_second_max,negative_max,negative_second_max。最后,如果(positive_max * positive_second_max)大于(negative_max * negative_second_max),则返回正对,否则返回负对。

示例

#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);
}

输出结果

(-5, -4)