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,939 questions

51,876 answers

573 users

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

2 Answers

0 votes
public class Program {
    static int item1 = 0, item2 = 0;
    
    public 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]; 
             }
          }
        }
    } 

    public static void main(String args[]) {
       int[] arr = {3, 9, 1, 3, 7, 0, 8, 4}; 

        max_product_from_int_array(arr);
     
        System.out.println(item1 + " " + item2);
    }
}


/*
run:

9 8

*/

 



answered Apr 15, 2019 by avibootz
edited Dec 26, 2025 by avibootz
0 votes
public class Program  {

    public static int[] maxProductPair(int[] arr) {
        if (arr == null || arr.length < 2) {
            throw new IllegalArgumentException("Array must contain at least two elements");
        }
    
        int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;
        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
    
        for (int x : 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)
                ? new int[] { max1, max2 }
                : new int[] { min1, min2 };
    }

   public static void main(String[] args) {
        int[] arr = { 3, 9, 1, 3, 7, 0, 4 };
    
        int[] pair = maxProductPair(arr);
        
        System.out.println("Max product pair: " + pair[0] + ", " + pair[1]);
    }
}



/*
run:

Max product pair: 9, 7

*/

 



answered Dec 26, 2025 by avibootz
...