Learn-dsa..in 30 days!



























CC-17 : Find maximum product of 2 elements in an array.

Description:

Given input integer array arr, find the maximum product of 2 integers that are part of this array.

Test cases and expected outputs:

Input Parameters Expected outputs
arr={1,2,3,4} Max product is 4 * 3 = 12
arr={-1,-2,-3,-4} Max product is -4 * -3 = 12
arr={-3,-2,-1,0,1,2,3} Max product is -3 * -2 = 6

Pseudocode:

The java method should accept following input parameters: arr1 (int array).
Initialize two variables names max and secMax to Integer.MIN.
Initialize two variables named min and secMin to Integer.MAX.
Iterate through arr using for loop and index idx:
If arr[idx]>max:
set secMax=max.
set max=arr[idx].
else if arr[idx] >secMax:
set secMax=arr[idx].
If arr[idx]< min:
set secMin=min.
set min=arr[idx].
o else if arr[idx] < secMin:
 set secMin=arr[idx].
If (max*secMax > min*secMin) return max and secMax.
Else return min and secMin.

Code:

public int[] arrayFindMaxProduct(int[] arr) throws Exception{
	int max=Integer.MIN_VALUE; int secMax=Integer.MIN_VALUE;
	int min=Integer.MAX_VALUE; int secMin=Integer.MAX_VALUE;
	
	for (int idx=0; idx < arr.length; idx++) {
		if (arr[idx] > max) {
			secMax=max;
			max=arr[idx];			
		}else if (arr[idx] > secMax) {
			secMax=arr[idx];
		}
		if (arr[idx] < min) {
			secMin=min;	
			min=arr[idx];					
		}else if (arr[idx] < secMin){
			secMin=arr[idx];			
		}
	}
	int prodMax=max*secMax;	int prodMin=min*secMin;
	int[] retArr=new int[2];
	if (prodMax > prodMin) {
		retArr[0]=max; 	retArr[1]=secMax;			
	}else {
		retArr[0]=min;
		retArr[1]=secMin;		
	}
	return retArr;	
}

Click here to download and run code and test cases !