This is not an original problem. I had a complex problem which is now reduced to the following:
There are two sorted arrays, A and B with m and n elements respectively, m = \Theta(n)
Can an algorithm that runs in o(mn) time find the maximum number of pairs such that A[i]-B[j] <= T where T is some constant? How can this be done?
edit:
-
The pairs should be disjoint, i.e. one element can be selected at most once.
-
The algorithm should run in little-o(mn) meaning that a solution that runs in mn time is not acceptable.
-
Is it also possible to find the pairs that we select?
Clarification:
If the arrays are a_1, a_2, ..., a_m and b_1, b_2, ..., b_n, I need to find pairs (a_i, b_j) such that |a_i - b_j| <= T. It is not allowed to choose an element more than once. How can we maximize the number of pairs given the arrays?
UPDATE 2:
The updated question (only use an element from either array once, get the pairs, and the absolute difference of the values must be below
T) might be able to be done in O(n+m) time. I haven’t thought through the algorithm below enough to decide if it will always get the maximum number of pairs or not, but it should in most cases: