Open In App

Maximum possible pair sum at most K from two Arrays

Improve
Improve
Like Article
Like
Save
Share
Report

Given two arrays arr1[] and arr2[] of sizes N and M and an integer K, the task is to find the maximum possible sum pair from two arrays such that the sum is at most K.

Note: You have to take one element from each array.

Examples: 

Input: arr1[] = {5, 4, 1, 2, 3}, arr2[] = {30, 20, 40, 10}, K = 30
Output: 25
Explanation: Maximum sum of a pair is (20 + 5) = 25 that is at most 30.

Input: toffee[] = {7, 6, 8}, candy[] = {9, 1, 5, 2, 8}, K = 5
Output: -1
Explanation: There is no such pair which have a pair sum less than or equal to 5

 

Approach: The basic idea to solve the problem is mentioned below:

Create all the possible pairs from arr1[] and arr2[]. From these pairs find a pair whose sum is the greatest and at most equal to K.

Follow the steps to solve the problem:

  • Define a variable (say sum = 0)to store the pair sum.
  • Traverse the array arr1[] from i = 0 to N:
    • For each element of arr1[] traverse from j = 0 to M of arr2[] to form all possible pairs and:
      • Calculate the pair sum of arr1[i] and arr2[j].
      • If the sum is greater than the maximum pair sum till now and not greater than K, update the maximum value.
  • After the loop ends, return the maximum value as the answer.

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find maximum amount
int maximumAmount(int arr1[], int arr2[],
                  int k, int n, int m)
{
 
    // ans stores final answer
    // sum will store current pair sum
    // of toffee and candy
    int ans = INT_MIN, sum;
 
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
 
            // Current pair sum of toffee
            // and candy
            sum = arr1[i] + arr2[j];
 
            // If sum is greater than ans
            // and sum is not greater than k
            // then change ans to sum
            if (sum > ans && sum <= k)
                ans = sum;
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    int arr1[] = { 5, 4, 1, 2, 3 };
    int arr2[] = { 30, 20, 40, 10 };
 
    int N = sizeof(arr1) / sizeof(arr1[0]);
    int M = sizeof(arr2) / sizeof(arr2[0]);
 
    int K = 30;
 
    // Function Call
    cout << maximumAmount(arr1, arr2, K, N, M);
 
    return 0;
}


Java




// Java program for above approach
import java.util.ArrayList;
 
class GFG {
 
// Function to find maximum amount
static int maximumAmount(int arr1[], int arr2[],
                  int k, int n, int m)
{
 
    // ans stores final answer
    // sum will store current pair sum
    // of toffee and candy
    int ans = Integer.MIN_VALUE, sum;
 
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
 
            // Current pair sum of toffee
            // and candy
            sum = arr1[i] + arr2[j];
 
            // If sum is greater than ans
            // and sum is not greater than k
            // then change ans to sum
            if (sum > ans && sum <= k)
                ans = sum;
        }
    }
    return ans;
}
 
// Driver code
public static void main(String args[]) {
 
    int arr1[] = { 5, 4, 1, 2, 3 };
    int arr2[] = { 30, 20, 40, 10 };
 
    int N = arr1.length;
    int M = arr2.length;
 
    int K = 30;
 
    // Function Call
    System.out.print(maximumAmount(arr1, arr2, K, N, M));
 
}
}
 
// This code is contributed by code_hunt.


Python3




# Python3 code to implement the approach
import sys
 
# Function to find maximum amount
def maximumAmount(arr1, arr2,k, n, m) :
 
    # ans stores final answer
    # sum will store current pair sum
    # of toffee and candy
    ans = -sys.maxsize;
    sum = 0;
 
    for i in range(n) :
        for j in range(m) :
 
            # Current pair sum of toffee
            # and candy
            sum = arr1[i] + arr2[j];
 
            # If sum is greater than ans
            # and sum is not greater than k
            # then change ans to sum
            if (sum > ans and sum <= k) :
                ans = sum;
         
    return ans;
 
# Driver code
if __name__ == "__main__" :
 
    arr1 = [ 5, 4, 1, 2, 3 ];
    arr2 = [ 30, 20, 40, 10 ];
 
    N = len(arr1);
    M = len(arr2);
 
    K = 30;
 
    # Function Call
    print(maximumAmount(arr1, arr2, K, N, M));
 
    # This code is contributed by AnkThon


C#




// C# program for above approach
using System;
 
public class GFG {
 
  // Function to find maximum amount
  static int maximumAmount(int []arr1, int []arr2,
                           int k, int n, int m)
  {
 
    // ans stores final answer
    // sum will store current pair sum
    // of toffee and candy
    int ans = int.MinValue;
    int sum;
 
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
 
        // Current pair sum of toffee
        // and candy
        sum = arr1[i] + arr2[j];
 
        // If sum is greater than ans
        // and sum is not greater than k
        // then change ans to sum
        if (sum > ans && sum <= k)
          ans = sum;
      }
    }
    return ans;
  }
 
  // Driver code
  public static void Main(string []arg) {
 
    int []arr1 = { 5, 4, 1, 2, 3 };
    int []arr2 = { 30, 20, 40, 10 };
 
    int N = arr1.Length;
    int M = arr2.Length;
 
    int K = 30;
 
    // Function Call
    Console.WriteLine(maximumAmount(arr1, arr2, K, N, M));
 
  }
}
 
// This code is contributed by AnkThon


Javascript




// JavaScript implementation of the approach
// Function to find maximum amount
function maximumAmount( arr1, arr2, k, n, m)
{
 
    // ans stores final answer
    // sum will store current pair sum
    // of toffee and candy
    let ans = Number.MIN_SAFE_INTEGER,
    let sum;
 
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
 
            // Current pair sum of toffee
            // and candy
            sum = arr1[i] + arr2[j];
 
            // If sum is greater than ans
            // and sum is not greater than k
            // then change ans to sum
            if (sum > ans && sum <= k)
                ans = sum;
        }
    }
    return ans;
}
 
// Driver code
 
    let arr1 =  [5, 4, 1, 2, 3 ];
    let  arr2 = [30, 20, 40, 10 ];
 
    let  N = arr1.length;
    let  M = arr2.length;
 
    let K = 30;
 
    // Function Call
     let ans = maximumAmount(arr1, arr2, K, N, M);
     document.write(ans);
     
    // This code is contributed by satwik4409.
     </script>


Output

25

Time Complexity: O(N*M)
Auxiliary Space: O(1)

New Approach:- Here an alternative approach to solve the problem of finding the maximum possible pair sum at most K from two arrays is to use sorting and two-pointer technique.

The steps to solve the problem using this approach are:

  • Sort both the arrays arr1[] and arr2[] in non-decreasing order.
  • Initialize two pointers i and j, pointing to the end of the arr1[] and arr2[] respectively.
  • Traverse the arrays by moving the pointers i and j towards the beginning of the arrays, and calculate the pair sum of arr1[i] and arr2[j].
  • If the sum is greater than K, then decrement j, else update the maximum pair sum.
  • Repeat steps 3 and 4 until either i or j becomes negative.
  • Return the maximum pair sum.

Below is the implementation of the above approach.

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to find maximum amount
int maximumAmount(int arr1[], int arr2[], int k, int n,
                  int m)
{
  // Sort both the arrays
  sort(arr1, arr1 + n);
  sort(arr2, arr2 + m);
 
  // Initialize pointers i and j
  int i = n - 1, j = m - 1;
 
  // Initialize ans to minimum value
  int ans = INT_MIN;
 
  // Traverse the arrays using two-pointer technique
  while (i >= 0 && j >= 0) {
 
    // Current pair sum of toffee
    // and candy
    int sum = arr1[i] + arr2[j];
 
    // If sum is less than or equal to K,
    // update the maximum pair sum
    if (sum <= k)
      ans = max(ans, sum);
 
    // If sum is greater than K,
    // decrement j
    if (sum > k)
      j--;
 
    // If sum is less than or equal to K,
    // decrement i
    else
      i--;
  }
  return ans;
}
 
// Driver code
int main()
{
  int arr1[] = { 5, 4, 1, 2, 3 };
  int arr2[] = { 30, 20, 40, 10 };
 
  int N = sizeof(arr1) / sizeof(arr1[0]);
  int M = sizeof(arr2) / sizeof(arr2[0]);
 
  int K = 30;
 
  // Function Call
  cout << maximumAmount(arr1, arr2, K, N, M);
}


Java




// Java program for above approach
import java.util.Arrays;
 
class GFG {
 
    // Function to find maximum amount
    static int maximumAmount(int arr1[], int arr2[], int k,
                             int n, int m)
    {
        // Sort both the arrays
        Arrays.sort(arr1);
        Arrays.sort(arr2);
 
        // Initialize pointers i and j
        int i = n - 1, j = m - 1;
 
        // Initialize ans to minimum value
        int ans = Integer.MIN_VALUE;
 
        // Traverse the arrays using two-pointer technique
        while (i >= 0 && j >= 0) {
 
            // Current pair sum of toffee
            // and candy
            int sum = arr1[i] + arr2[j];
 
            // If sum is less than or equal to K,
            // update the maximum pair sum
            if (sum <= k)
                ans = Math.max(ans, sum);
 
            // If sum is greater than K,
            // decrement j
            if (sum > k)
                j--;
 
            // If sum is less than or equal to K,
            // decrement i
            else
                i--;
        }
        return ans;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int arr1[] = { 5, 4, 1, 2, 3 };
        int arr2[] = { 30, 20, 40, 10 };
 
        int N = arr1.length;
        int M = arr2.length;
 
        int K = 30;
 
        // Function Call
        System.out.print(
            maximumAmount(arr1, arr2, K, N, M));
    }
}


Python3




# Function to find maximum amount
def maximumAmount(arr1, arr2, k, n, m):
    # Sort both the arrays
    arr1.sort()
    arr2.sort()
 
    # Initialize pointers i and j
    i, j = n - 1, m - 1
 
    # Initialize ans to minimum value
    ans = float('-inf')
 
    # Traverse the arrays using two-pointer technique
    while i >= 0 and j >= 0:
        # Current pair sum of toffee and candy
        pair_sum = arr1[i] + arr2[j]
 
        # If sum is less than or equal to k,
        # update the maximum pair sum
        if pair_sum <= k:
            ans = max(ans, pair_sum)
 
        # If sum is greater than k,
        # decrement j
        if pair_sum > k:
            j -= 1
 
        # If sum is less than or equal to k,
        # decrement i
        else:
            i -= 1
 
    return ans
 
 
# Driver code
arr1 = [5, 4, 1, 2, 3]
arr2 = [30, 20, 40, 10]
N = len(arr1)
M = len(arr2)
K = 30
 
# Function Call
print(maximumAmount(arr1, arr2, K, N, M))


C#




using System;
 
public class Program {
    public static int MaximumAmount(int[] arr1, int[] arr2,
                                    int k, int n, int m)
    {
        // Sort both the arrays
        Array.Sort(arr1);
        Array.Sort(arr2);
 
        // Initialize pointers i and j
        int i = n - 1, j = m - 1;
 
        // Initialize ans to minimum value
        int ans = int.MinValue;
 
        // Traverse the arrays using two-pointer technique
        while (i >= 0 && j >= 0) {
            // Current pair sum of toffee and candy
            int pairSum = arr1[i] + arr2[j];
 
            // If sum is less than or equal to k,
            // update the maximum pair sum
            if (pairSum <= k) {
                ans = Math.Max(ans, pairSum);
            }
 
            // If sum is greater than k,
            // decrement j
            if (pairSum > k) {
                j--;
            }
 
            // If sum is less than or equal to k,
            // decrement i
            else {
                i--;
            }
        }
 
        return ans;
    }
 
    public static void Main()
    {
        int[] arr1 = { 5, 4, 1, 2, 3 };
        int[] arr2 = { 30, 20, 40, 10 };
        int n = arr1.Length;
        int m = arr2.Length;
        int k = 30;
 
        // Function Call
        Console.WriteLine(
            MaximumAmount(arr1, arr2, k, n, m));
    }
}


Javascript




// Function to find maximum amount
function maximumAmount(arr1, arr2, k) {
  // Sort both arrays in ascending order
  arr1.sort((a, b) => a - b);
  arr2.sort((a, b) => a - b);
 
  // Initialize pointers i and j
  let i = arr1.length - 1;
  let j = arr2.length - 1;
 
  // Initialize ans to a minimum value
  let ans = Number.MIN_SAFE_INTEGER;
 
  // Traverse the arrays using two-pointer technique
  while (i >= 0 && j >= 0) {
    // Calculate the current pair sum of toffee and candy
    let sum = arr1[i] + arr2[j];
 
    // If the sum is less than or equal to K, update the maximum pair sum
    if (sum <= k) {
      ans = Math.max(ans, sum);
    }
 
    // If the sum is greater than K, decrement j
    if (sum > k) {
      j--;
    }
    // If the sum is less than or equal to K, decrement i
    else {
      i--;
    }
  }
  return ans;
}
 
// Driver code
const arr1 = [5, 4, 1, 2, 3];
const arr2 = [30, 20, 40, 10];
const K = 30;
 
// Function call
console.log(maximumAmount(arr1, arr2, K));


Output:-

25

Time Complexity:  The time complexity of the given solution is O(N log N + M log M), where N and M are the sizes of the input arrays arr1 and arr2, respectively. The sorting of the arrays takes O(N log N + M log M) time, and the while loop takes O(N + M) time. Since O(N + M) is dominated by O(N log N + M log M), the overall time complexity is O(N log N + M log M).
Auxiliary Space:  The auxiliary space used by the solution is O(1), as we are not using any additional data structures and are only using a constant amount of memory to store the pointers and the maximum pair sum.



Last Updated : 29 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads