How to find a pair with maximum product from int array in C++

2 Answers

0 votes
#include <iostream>

void max_product_from_int_array(int arr[], int len, int *item1, int *item2) { 
    *item1 = arr[0], *item2 = arr[1]; 
   
    for (int i = 0; i < len; i++) 
      for (int j = i + 1; j < len; j++) 
         if (arr[i] * arr[j] > *item1 * *item2) 
            *item1 = arr[i], *item2 = arr[j]; 
} 
   
int main() 
{ 
    int arr[] = {3, 9, 1, 3, 7, 0, 4}; 
    int len = sizeof(arr) / sizeof(arr[0]); 
    int item1 = 0, item2 = 0;
     
    max_product_from_int_array(arr, len, &item1, &item2);
     
    std::cout << item1 << " " << item2;
} 
 
 
/*
run:
 
9 7
 
*/

 



answered Apr 14, 2019 by avibootz
edited Dec 26, 2025 by avibootz
0 votes
#include <iostream>
#include <climits>

void maxProductPair(int arr[], int size, int *item1, int *item2) {
    if (size < 2) {
        std::cout << "Array must have at least two elements\n";
        return;
    }

    int max1 = INT_MIN, max2 = INT_MIN;
    int min1 = INT_MAX, min2 = INT_MAX;

    for (int i = 0; i < size; i++) {
        int x = arr[i];

        // Update max values
        if (x > max1) {
            max2 = max1;
            max1 = x;
        } else if (x > max2) {
            max2 = x;
        }

        // Update min values
        if (x < min1) {
            min2 = min1;
            min1 = x;
        } else if (x < min2) {
            min2 = x;
        }
    }

    long long prodMax = 1LL * max1 * max2;
    long long prodMin = 1LL * min1 * min2;

    if (prodMax > prodMin) {
        *item1 = max1;
        *item2 = max2;
    } else {
        *item1 = min1;
        *item2 = min2;
    }
}

int main() {
    int arr[] = {3, 9, 1, 3, 7, 0, 4}; 
    int size = sizeof(arr) / sizeof(arr[0]); 
    int item1 = 0, item2 = 0;
    
    maxProductPair(arr, size, &item1, &item2);
    std::cout << item1 << " " << item2;
}

 
 
/*
run:
 
9 7
 
*/

 



answered Dec 26, 2025 by avibootz
edited Dec 26, 2025 by avibootz
...