Computer >> Máy Tính >  >> Lập trình >> C ++

Tìm một cặp có tích tối đa trong mảng Số nguyên trong C ++

Xét ta có một mảng A, có n phần tử khác nhau. Chúng ta phải tìm một cặp (x, y) từ mảng A sao cho tích của x và y là lớn nhất. Mảng có thể chứa các phần tử dương hoặc âm. Giả sử một mảng như sau:A =[-1, -4, -3, 0, 2, -5], thì cặp này sẽ là (-4, -5) vì tích là cực đại.

Để giải quyết vấn đề này, chúng ta phải theo dõi bốn số, positive_max, positive_second_max, negative_max, negative_second_max. Cuối cùng, nếu (positive_max * positive_second_max) lớn hơn (negative_max * negative_second_max), thì trả về các cặp dương, nếu không thì trả về các cặp âm.

Ví dụ

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

Đầu ra

(-5, -4)