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.
- For each element of arr1[] traverse from j = 0 to M of arr2[] to form all possible pairs and:
- After the loop ends, return the maximum value as the answer.
Below is the implementation of the above approach.
C++
|
Time Complexity: O(N*M)
Auxiliary Space: O(1)