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
using System;

class Program
{
    static int item1 = 0, item2 = 0;
     
    static void max_product_from_int_array(int[] arr) { 
        item1 = arr[0];
        item2 = arr[1]; 
        int len =  arr.Length;
         
        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]; 
             }
          }
        }
    } 
    static void Main()
    {
        int[] arr = {3, 9, 1, 3, 7, 0, 8, 4}; 
 
        max_product_from_int_array(arr);

        Console.Write(item1 + " " + item2);
    }
}



/*
run:

9 8

*/

 



answered Apr 15, 2019 by avibootz
0 votes
using System;

class Program
{
    public static (int First, int Second) MaxProductPair(int[] arr) {
        if (arr == null || arr.Length < 2)
            throw new ArgumentException("Array must contain at least two elements.");
    
        int max1 = int.MinValue, max2 = int.MinValue;
        int min1 = int.MaxValue, min2 = int.MaxValue;
    
        foreach (int x in arr) {
            // 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 prodMax = (long)max1 * max2;
        long prodMin = (long)min1 * min2;
    
        return prodMax >= prodMin
            ? (max1, max2)
            : (min1, min2);
    }

    static void Main()
    {
        var arr = new[] { 3, 9, 1, 3, 8, 0, 4 };

        var pair = MaxProductPair(arr);

        Console.WriteLine($"Max product pair: {pair.First}, {pair.Second}");
    }
}



/*
run:

Max product pair: 9, 8

*/

 



answered Dec 26, 2025 by avibootz
...