Given as input, a sorted array of floats, I need to find the total number of pairs (i,j)
such as A[i]*A[j]>=A[i]+A[j]
for each i < j
Here's a binary search, O(n log n):
There's a breaking point for each number at A*B = A+B
. You can reduce this to B = A / (A - 1)
. All numbers on one side or the other will fit it. It doesn't matter if there are negative numbers, etc.
If A < 1
, then all numbers <= B
fit.
If A > 1
, then all numbers >= B
fit.
If A == 1
, then there is no match(divide by zero).
(Wolfram Alpha link)
So some pseudocode:
loop through i
a = A[i]
if(a == 1)
continue
if(a >= 2)
count += A.length - i
continue
j = binsearch(a / (a-1))
if(j <= i)
continue
if(a < 1)
count += j-i
if(a > 1)
count += A.length - j