Given an array of integers. count number of perfect pairs from the array, the Perfect Pairs is a pair of integers (x, y) if both of the following conditions are met:
min(|x-y|,|x+y|) <=min(|x|,|y|)
max(|x-y|,|x+y|) >= max(|x|,|y|)
my Solution is:
public int perfectPair(int[] arr){
int perfectPairCount = 0;
for(int i=1; i<arr.length; i++){
int absY = Math.abs(arr[i]);
for(int j=0; j<i; j++){
int xPlusY = Math.abs(arr[j] + arr[i]);
int xMinusY = Math.abs(arr[j] - arr[i]);
int absX = Math.abs(arr[j]);
if(Math.min(xPlusY, xMinusY) <= Math.min(absX, absY) && Math.max(xPlusY, xMinusY) >= Math.max(absX, absY)){
perfectPairCount++;
}
}
}
return perfectPairCount;
}
This code in running in O^2 time and the code is throwing the TimeLimitExceededException for very large input size.
I am looking for the optimized code for this problem.
2