Maximum product of any pair
Java
Hard
4 views
Problem Description
Task: values can be negative. Return maximum product of any two elements.
Output Format
Return value
Constraints
Array length >= 2.
Official Solution
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;}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!