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
*/