Finding pairs with product greater than sum

前端 未结 5 1995
长发绾君心
长发绾君心 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:21

    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
    

提交回复
热议问题