Maximum product of any pair

Maximum product of any pair

Hard Java Arrays 21 views
Explanation Complexity

Problem Statement

Task: values can be negative. Return maximum product of any two elements.

Input Format

An integer n (size of array)
Then n integers (array elements, can be negative)

Output Format

Maximum product of any two elements.

Example

5
-10 -3 5 6 -2
30

Constraints

• n ≥ 2

• Elements can be negative, zero, or positive

Concept Explanation

The maximum product can come from:

• the two largest positive numbers, or

• the two smallest (most negative) numbers
(because negative × negative = positive).

Step-by-Step Explanation

1.Read array size n and elements.

2.Initialize:

• max1 = Integer.MIN_VALUE

• max2 = Integer.MIN_VALUE

• min1 = Integer.MAX_VALUE

• min2 = Integer.MAX_VALUE

3.Loop through the array once:

• Update the two largest values (max1, max2).

• Update the two smallest values (min1, min2).

4.Compute:

• product1 = max1 * max2

• product2 = min1 * min2

5.The answer is max(product1, product2).

6.Print the result.

Concept Explanation

The maximum product can come from:

• the two largest positive numbers, or

• the two smallest (most negative) numbers
(because negative × negative = positive).

Step-by-Step Explanation

1.Read array size n and elements.

2.Initialize:

• max1 = Integer.MIN_VALUE

• max2 = Integer.MIN_VALUE

• min1 = Integer.MAX_VALUE

• min2 = Integer.MAX_VALUE

3.Loop through the array once:

• Update the two largest values (max1, max2).

• Update the two smallest values (min1, min2).

4.Compute:

• product1 = max1 * max2

• product2 = min1 * min2

5.The answer is max(product1, product2).

6.Print the result.

Input / Output Format

Input Format
An integer n (size of array)
Then n integers (array elements, can be negative)
Output Format
Maximum product of any two elements.
Constraints
• n ≥ 2

• Elements can be negative, zero, or positive

Examples

Input:
5 -10 -3 5 6 -2
Output:
30

Example Solution (Public)

Java
static long maxPairProduct(int[] a){int max1=Integer.MIN_VALUE,max2=Integer.MIN_VALUE,min1=Integer.MAX_VALUE,min2=Integer.MAX_VALUE;for(int x:a){if(x>max1){max2=max1;max1=x;}else if(x>max2){max2=x;}if(x<min1){min2=min1;min1=x;}else if(x<min2){min2=x;}}long p1=1L*max1*max2;long p2=1L*min1*min2;return p1>p2?p1:p2;}

Official Solution Code

static long maxPairProduct(int[] a){int max1=Integer.MIN_VALUE,max2=Integer.MIN_VALUE,min1=Integer.MAX_VALUE,min2=Integer.MAX_VALUE;for(int x:a){if(x>max1){max2=max1;max1=x;}else if(x>max2){max2=x;}if(x<min1){min2=min1;min1=x;}else if(x<min2){min2=x;}}long p1=1L*max1*max2;long p2=1L*min1*min2;return p1>p2?p1:p2;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.