Highest Product

Given an array A, of N integers A.

Return the highest product possible by multiplying 3 numbers from the array.

NOTE: Solution will fit in a 32-bit signed integer.

Input Format:

The first and the only argument is an integer array A.

Output Format:

Return the highest possible product.

Constraints:

1 <= N <= 5e5

Example:

Input 1:
A = [1, 2, 3, 4]

Output 1:
24

Explanation 1:
2 * 3 * 4 = 24

Input 2:
A = [0, -1, 3, 100, 70, 50]

Output 2:
350000

Explanation 2:
70 * 50 * 100 = 350000
class Solution {
    public int maxp3(int[] A) {
        if (A.length < 3)
            return -1;
        int maxA = Integer.MIN_VALUE, maxB = Integer.MIN_VALUE, maxC = Integer.MIN_VALUE;
        int minA = Integer.MAX_VALUE, minB = Integer.MAX_VALUE;
        for (int x : A) {
            if (x > maxA) {
                maxC = maxB;
                maxB = maxA;
                maxA = x;
            } else if (x > maxB) {
                maxC = maxB;
                maxB = x;
            } else if (x > maxC)
                maxC = x;

            if (x < minA) {
                minB = minA;
                minA = x;
            } else if (x < minB)
                minB = x;
        }
        return Math.max(minA * minB * maxA, maxA * maxB * maxC);
    }
}

Last updated