Finding pairs with product greater than sum

前端 未结 5 2000
长发绾君心
长发绾君心 2020-12-13 22:04

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

5条回答
  •  不思量自难忘°
    2020-12-13 22:17

    Here's a O(n) algorithm that solves the problem when the array's elements are positive.

    When the elements are positive, we can say that:

    • If A[i]*A[j] >= A[i]+A[j] when j>i then A[k]*A[j] >= A[k]+A[j] for any k that satisfies k>i (because the array is sorted).

    • If A[i]*A[j] < A[i]+A[j] when j>i then A[i]*A[k] < A[i]+A[k] for any k that satisfies k.

    (these facts don't hold when both numbers are fractions, but then the condition won't be satisfied anyway)

    Thus we can perform the following algorithm:

    int findNumOfPairs(float A[])
    {    
        start = 0;
        end = A.length - 1;
        numOfPairs = 0;
    
        while (start != end)
        {
            if (A[start]*A[end] >= A[start]+A[end])
            {
                numOfPairs += end - start;
                end--;
            }
            else
            {
                start++;
            }
        }
    
        return numOfPairs;
    }
    

提交回复
热议问题