Search code examples
c++dynamic-programmingdivide-and-conquer

To reduce the time complexity


I have a question in which I am given a set of values SET A, and a set of values SET B. I am supposed to find the maximum number of pairs possible taking one value from set A and one value with set B. Condition- The difference between the two values should be less than 11.

eg- SET A-2,3,4 SET B-14,12,250 Max Pairs possible- (14,4) and (12,3) NOTE-(12,4) can also be a pair but then,it wont give us maximum possible sets, as 3 would be left. Therefor two achieve maximum 4 pairs up with 14 and 12 with 3.

I am able to solve this question in O(n^2) complexity, I was looking for a better solution.


Solution

  • I answered a similar question 10 minutes ago. The ides here is the same: loop over sorted ranges.

    Here is the same code as in the other answer adapted to your problem (I just replaced the equality by a smaller-than relation):

    auto find_pairs(std::vector<int>& arr1, std::vector<int>& arr2, int diff)
    {
        std::vector<std::pair<int,int> > ret;
    
        std::sort(std::begin(arr1), std::end(arr1));
        std::sort(std::begin(arr2), std::end(arr2));
    
        auto it1= std::begin(arr1);
        auto it2= std::begin(arr2);
    
        while(it1!= std::end(arr1) && it2!= std::end(arr2))
        {
            if(std::abs(*it1-*it2) < diff)
            {
                ret.push_back(std::make_pair(*it1,*it2));
                ++it1;
                ++it2;
            }
            else if(*it1<*it2)
            {
                ++it1;
            }
            else
            {
                ++it2;
            }
        }
    
        return ret;
    }
    

    Here is the application for your example,

    int main()
    {
    
        std::vector<int> arr1 = {2,3,4};   
        std::vector<int> arr2 = {14,12,250};   
        int diff=11;
    
        auto pairs = find_pairs(arr1, arr2, diff);
    
        for(auto& i : pairs)
        {
            std::cout<<i.first<<"  "<<i.second<<std::endl;
        }    
    }
    

    With this one obtains the desired answer given in the OP:

    2  12
    4  14
    

    DEMO.