Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

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

2 Answers

0 votes
#include <stdio.h>

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, 8, 4}; 
    int len = sizeof(arr)/sizeof(arr[0]); 
    int item1 = 0, item2 = 0;
    
    max_product_from_int_array(arr, len, &item1, &item2);
    
    printf("%2i%2i", item1, item2);
    
    return 0; 
} 


/*
run:

 9 8

*/

 



answered Apr 15, 2019 by avibootz
edited Apr 15, 2019 by avibootz
0 votes
#include <limits.h>

void max_product_pair(int arr[], int size, int *item1, int *item2)
{
    if (size < 2) {
        *item1 = *item2 = 0;  /* or handle error differently */
        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];

        /* Track two largest values */
        if (x > max1) {
            max2 = max1;
            max1 = x;
        } else if (x > max2) {
            max2 = x;
        }

        /* Track two smallest values */
        if (x < min1) {
            min2 = min1;
            min1 = x;
        } else if (x < min2) {
            min2 = x;
        }
    }

    long long prod_max = (long long)max1 * max2;
    long long prod_min = (long long)min1 * min2;

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


#include <stdio.h>

int main(void)
{
    int arr[] = { 3, 9, 1, 3, 7, 0, 4 };
    int size = sizeof(arr) / sizeof(arr[0]); 
    int a, b;

    max_product_pair(arr, size, &a, &b);

    printf("Max product pair: %d, %d\n", a, b);
    
    return 0;
}



/*
run:

Max product pair: 9, 7

*/

 



answered Dec 26, 2025 by avibootz
...