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
You can find and print the pairs (in a shorthand form) in O(n log n)
.
For each A[i]
there is a minimum number k
that satisfies the condition(1).
All values greater than k will also satisfy the condition.
Finding the lowest j
such that A[j] >= k using binary search is O(log n)
.
So you can find and print the result like this:
(i, j)
(1, no match)
(2, no match)
(3, >=25)
(4, >=20)
(5, >=12)
(6, >6)
(7, >7)
...
(n-1, n)
If you want to print all combinations, then it is O(n^2), because the number of combinations are O(n^2).
(*) To handle negative numbers it actually needs to be a bit more complex, because the numbers that satify the equation can be more that one range. I'm not absolutely sure how it behaves for small negative numbers, but if the number of ranges is not absolutely limited then my solution is no longer better than O(n^2).