Return the total number of pairs (a, b) where a is from A and b is from B, and a + b is <= c

Elroy Jetson :

Trying to do some practice and I ran across this problem...

Given two int arrays A and B, and an int c, return the total number of pairs (a, b) where a is from A and b is from B, and a + b is <= c

Came up with brute force solution immediately, but can't seem to connect the dots in order to do this in better time complexity. I tried sorting the arrays first, and trying to find some type of pattern but that didn't get me anywhere. I thought about cases where one array had negative numbers. In this case, I cant just look at a value from A or B and check if it itself is less than c, because there may be a negative value in the other array that when added together gives me a result of <= c. Any insight, or ideas, or clues would be appreciated.

import java.util.*;

public class CountPairs {

    public static void main(String args[]){
        int arrayA[] = {32,45,9,4};
        int arrayB[] = {43,457,54,90};

        Scanner scan = new Scanner(System.in);

        System.out.println("Choose the value that you want to find pairs <= ");
        int c = scan.nextInt();

        System.out.println("The total number of pairs are : " + pairs(arrayA, arrayB, c));
    }

    public static int pairs(int A[], int B[], int n) {
        int count = 0;

        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < B.length; j++) {
                int total = A[i] + B[j];

                if(total <= n)
                    count++;
            }
        }

        return count;
    }
}
גלעד ברקן :

We can solve this in O(m log m + n log m) = O(log m (m + n)) time where m is the cardinality of the smaller array; n, the larger. First, sort the smaller array:

A = {32,45,9,4};
B = {43,457,54,90};

=> A = {4,9,32,45}

Now for each b in B, use a binary search on A to find the index of the greatest a less than or equal to (c - b). Add (index + 1) to the accumulating result. For example:

c = 100:
  43  => 100 - 43  = 57   => largest a <= c-b = 45, index 3 => add 4 to result
  457 => 100 - 457 = -357 => largest a <= c-b = None
  54  => 100 - 54  = 46   => largest a <= c-b = 45, index 3 => add 4 to result
  90  => 100 - 90  = 10   => largest a <= c-b = 9,  index 1 => add 2 to result

result = 4 + 4 + 2 = 10
 corresponding with the following pairs:
 (43,4),(43,9),(43,32),(43,45),(54,4),(54,9),(54,32),(54,45),(90,4),(9,9)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=449699&siteId=1
B