Write a program to find the number of pairs of elements in an array, that satisfy the below condition.
min(∣a−b∣,∣a+b∣)≤min(∣a∣,∣b∣)
max(∣a−b∣,∣a+b∣)≥max(∣a∣,∣b∣)
min(∣a−b∣,∣a+b∣)≤min(∣a∣,∣b∣)≤max(∣a∣,∣b∣)≤max(∣a−b∣,∣a+b∣)
Example:
[-9, 6, -5, 3]
-9 -5
-9 6
-5 3
-5 6
3 6
constraints:
1<=N<=200000
-1000000000<=a[i]<=1000000000
Solved it with O(NxN)
Required Complexity: O(NlogN)
If anybody has better solution please share.
Auto comment: topic has been updated by prakash951 (previous revision, new revision, compare).
Auto comment: topic has been updated by prakash951 (previous revision, new revision, compare).
NlogN
Approach
1. Sort the given array in descending order with custom comparator that comapre for abs() value. So the sorted array will be [-9,6,-5,3](luckily in the given example it is already sorted accoridng to the comparator)
2.Only the first condition is neccesary because addition of two number is always greater than the numbermax(|a+b|,|a-b|) it is true for both positive and negative numbers.
3.for each number in the array we will apply Binary search on index+1-->end to avoid duplicate pairs.
4.Now start=index+1 and end=n-1 for a particular value. mid=start+(end-start)/2
5.if min(a-b)=min(a,b) it means the difference is the biggest value that can be the answer. It means every small value is also the answer beacuse we want lesser or equal.
6.if min(a-b)>min(a-b) it means the answer is in the left part of array because the difference is too big.
I hope it helps because i tryed my best to do it. plz tell me if my code is right or wrong.