Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Find the pairs of IDs from two arrays having sum less than target closest to it

  • Last Updated : 27 Sep, 2021

Given two arrays arr1[] and arr2[] of pairs of the form {ID, value} of size N and M respectively and an integer target, the task is to find all the pairs of IDs from both the arrays such that the sum of the values of the pairs is maximum and has a value at most M.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr1[] = [[1, 2000], [2, 3000], [3, 2000]], arr2[] = [[1, 2500], [2, 3000], [3, 3000]], target = 6000
Output:
2 2
2 3
Explanation:
Following are the pairs of elements from the two arrays arr1[] and arr2[]:



  • (arr1[2], arr2[2]): The sum of elements 3000 + 3000 = 6000(= target) and closest to the value target. Print the IDs as (2, 2).
  • (arr1[2], arr2[3]): The sum of elements 3000 + 3000 = 6000(= target) and closest to the value target. Print the IDs as (2, 3).

Input: arr1[] = [[1, 2000], [2, 3000], [3, 2000]], arr2[] = [[1, 3000], [2, 3000]], target = 5500
Output:
1 1
1 2
3 1
3 2

Approach: The given problem can be solved using the TreeMap Data Structure to store the array elements arr1[] and efficiently find the pair for every element in the other array arr2[]. Below are the steps:

  • Create a TreeMap where the key is the value of the array element and the value is the list of IDs.
  • Iterate the array arr1[] and insert its elements into the TreeMap.
  • Initialize a variable, say closestTarget to keep track of the closest value to the target and not exceeding it.
  • Initialize an ArrayList result to store all the possible pairs of IDs.
  • Iterate the array arr2[] and for every element calculate the remaining value to be searched in the TreeMap.
    • If the remaining value, say (target – arr2[i]) is less than 0, then the pair cannot be formed so continue the iteration.
    • Use the floorKey() function of the TreeMap to find a value less than or equal to the remaining value. If the returned value of the above function is null, then no corresponding element is found.
    • If the returned value, say currentTarget is greater than closestTarget, then update closestTarget and re-initialize the arrayList result[] to a new list.
    • Iterate through the list of ids whose key is currentTarget and add all possible combinations of IDs pairs into the result list.
  • After completing the above steps, print all the pairs of IDs stored in the ArrayList result[].

Below is the implementation of the above approach:

Java




// Java program for the above approach
  
import java.io.*;
import java.util.*;
  
class GFG {
  
    // Function to find pairs of ids with
    // sum of values closest to the target
    // but not exceeding the target
    public static void closestPair(
        int[][] arr1, int[][] arr2, int target)
    {
  
        // Initialize TreeMap having array
        // element value as key and list of
        // ids as value in the TreeMap
        TreeMap<Integer, List<Integer> > valueToIds
            = new TreeMap<>();
  
        // list to store all answer pairs
        List<int[]> result = new ArrayList<>();
  
        // Keeps the track of maximum sum
        // of pair values not exceeding target
        int closestTarget = 0;
  
        // Iterate through the array arr1 and
        // add all elements in the TreeMap
        for (int[] a : arr1) {
  
            int val = a[1], id = a[0];
            valueToIds.putIfAbsent(
                val, new ArrayList<>());
            valueToIds.get(val).add(id);
        }
  
        for (int[] b : arr2) {
  
            // Find the corresponding value
            // to be found
            int remaining = target - b[1];
  
            if (remaining < 0)
                continue;
  
            // Find a value which is close to
            // desired value, not exceeding it
            Integer floor = valueToIds.floorKey(
                remaining);
  
            // No value found which is less
            // than or equal to floor
            if (floor == null)
                continue;
  
            int currentTarget = b[1] + floor;
  
            if (currentTarget >= closestTarget) {
                if (currentTarget > closestTarget) {
  
                    // Update closeTarget and reset
                    // result list
                    closestTarget = currentTarget;
                    result = new ArrayList<>();
                }
  
                // Add all possible pairs in
                // result list
                for (int id : valueToIds.get(floor))
                    result.add(
                        new int[] { id, b[0] });
            }
        }
  
        // Print all the id pairs
        for (int[] ans : result) {
            System.out.println(
                ans[0] + " " + ans[1]);
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int[][] arr1
            = { { 1, 2000 }, { 2, 3000 }, { 3, 2000 } };
        int[][] arr2 = { { 1, 3000 },
                         { 2, 3000 } };
        int target = 5500;
  
        closestPair(arr1, arr2, target);
    }
}
Output:
1 1
3 1
1 2
3 2

Time Complexity: O(N*log N + M)
Auxiliary Space: O(N*M)




My Personal Notes arrow_drop_up
Recommended Articles
Page :