package algorithms;

import java.util.Arrays;

public class MaxPairwiseProduct {
	static long getMaxPairwiseProduct(Integer[] numbers) {
		if (numbers.length == 1) {
			return 0;
		}
		Arrays.sort(numbers, (x, y) -> x - y);
		int lastIndex = numbers.length - 1;
		long bigResult = (long) numbers[lastIndex] * numbers[lastIndex - 1];
		return bigResult;
	}

	public static void main(String[] args) {
		System.out.println(
				"Type number to calculate the maximum pairwise product. "
						+ "The first number is a total count of numbers.");
		FastScanner scanner = new FastScanner(System.in);
		int numberOfNumbers = scanner.popNextInt();
		if (numberOfNumbers > Integer.MAX_VALUE) {
			throw new IllegalArgumentException("Too many numbers, the max is: " + Integer.MAX_VALUE);
		}
		Integer[] numbers = new Integer[numberOfNumbers];
		for (int i = 0; i < numberOfNumbers; i++) {
			numbers[i] = scanner.popNextInt();
		}
		System.out.println(getMaxPairwiseProduct(numbers));
	}
}
@@ -18,34 +18,8 @@
 s;%0A%0A
-import java.util.Arrays;%0A%0A
 publ
@@ -156,131 +156,263 @@
 %7D%0A%09%09
-Arrays.sort(numbers, (x, y) -%3E x - y)
+Integer maxIndex1 = null
 ;%0A%09%09
-int last
+Integer max
 Index
+2
  = nu
-mbers.length - 1;%0A%09%09long bigResult = (long) numbers%5BlastIndex%5D *
+ll;%0A%09%09for (int i = 0; i %3C numbers.length; ++i) %7B%0A%09%09%09if (maxIndex1 == null %7C%7C numbers%5Bi%5D %3E numbers%5BmaxIndex1%5D) %7B%0A%09%09%09%09maxIndex2 = maxIndex1;%0A%09%09%09%09maxIndex1 = i;%0A%09%09%09%7D else if (maxIndex2 == null %7C%7C numbers%5Bi%5D %3E
  num
@@ -420,42 +420,109 @@
 ers%5B
-lastIndex - 1%5D;%0A%09%09return bigResult
+maxIndex2%5D) %7B%0A%09%09%09%09maxIndex2 = i;%0A%09%09%09%7D%0A%09%09%7D%0A%09%09return ((long) (numbers%5BmaxIndex1%5D)) * numbers%5BmaxIndex2%5D
 ;%0A%09%7D

Improve efficiency to constant O(n)