Maximum Product of Two Elements

easy Arrays

Problem

Choose two different positions. Print the largest possible product of their values. The array can contain negative numbers, so two big negative numbers can give the largest product.

Constraints

  • 2 <= n <= 10^5
  • |a[i]| <= 10^6

Examples

Input

5
0 2 -3 -5 4

Output

15

Solutions

Best approachTime O(n)Space O(1)

A common mistake is to look only at the two largest values. Two very negative numbers also give a big positive product. So we compare both candidates.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process an array.
 * Input   : n, then n integers.
 * Output  : The largest product.
 * Approach: Two largest or two smallest.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[] a) {
        // Step 1: Track the two largest and the two smallest values in one pass.
        long max1 = Long.MIN_VALUE;
        long max2 = Long.MIN_VALUE;
        long min1 = Long.MAX_VALUE;
        long min2 = Long.MAX_VALUE;

        for (int value : a) {
            if (value > max1) {
                max2 = max1;
                max1 = value;
            } else if (value > max2) {
                max2 = value;
            }
            if (value < min1) {
                min2 = min1;
                min1 = value;
            } else if (value < min2) {
                min2 = value;
            }
        }

        // Step 2: The answer is the product of the two largest, or of the two smallest (two negatives make a positive).
        return Math.max(max1 * max2, min1 * min2);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(solve(a));
    }
}
Hints (1)
  1. Why can two negative numbers win?