Maximum possible pair sum at most K from two Arrays
Last Updated :
29 Oct, 2023
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>
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.
Similar Reads
Count maximum possible pairs from an array having sum K
Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum number of pairs having a sum K possible from the given array. Note: Every array element can be part of a single pair. Examples: Input: arr[] = {1, 2, 3, 4}, K = 5Output: 2Explanation: Pairs with sum K fro
11 min read
Find Sum of pair from two arrays with maximum sum
Given two arrays of positive and distinct integers. The task is to find a pair from the two arrays with maximum sum. Note: The pair should contain one element from both the arrays. Examples: Input : arr1[] = {1, 2, 3}, arr2[] = {4, 5, 6} Output : Max Sum = 9 Pair (3, 6) has the maximum sum. Input :
6 min read
Maximum K-digit number possible from subsequences of two given arrays
Given two arrays arr1[] and arr2[] of length M and N consisting of digits [0, 9] representing two numbers and an integer K(K ? M + N), the task is to find the maximum K-digit number possible by selecting subsequences from the given arrays such that the relative order of the digits is the same as in
12 min read
K maximum sum combinations from two arrays
Given two integer arrays A and B of size N each. A sum combination is made by adding one element from array A and another element of array B. The task is to return the maximum K valid sum combinations from all the possible sum combinations.Note: Output array must be sorted in non-increasing order.Ex
12 min read
Maximum Prefix Sum possible by merging two given arrays
Given two arrays A[] and B[] consisting of N and M integers respectively, the task is to calculate the maximum prefix sum that can be obtained by merging the two arrays. Examples: Input : A[] = {2, -1, 4, -5}, B[]={4, -3, 12, 4, -3}Output : 22Explanation: Merging the two arrays to generate the seque
11 min read
Maximum sum by picking elements from two arrays in order | Set 2
Given two arrays A[] and B[], each of size N, and two integers X and Y denoting the maximum number of elements that can be picked from A[] and B[] respectively, the task is to find the maximum possible sum by selecting N elements in such a way that for any index i, either A[i] or B[i] can be chosen.
10 min read
Maximize number of elements from Array with sum at most K
Given an array A[] of N integers and an integer K, the task is to select the maximum number of elements from the array whose sum is at most K. Examples: Input: A[] = {1, 12, 5, 111, 200, 1000, 10}, K = 50 Output: 4 Explanation: Maximum number of selections will be 1, 12, 5, 10 that is 1 + 12 + 5 + 1
6 min read
Maximum sum combination from two arrays
Given two arrays arr1[] and arr2[] each of size N. The task is to choose some elements from both arrays such that no two elements have the same index and no two consecutive numbers can be selected from a single array. Find the maximum sum possible of the above-chosen numbers. Examples: Input : arr1[
10 min read
Maximum OR sum of sub-arrays of two different arrays
Given two arrays of positive integers. Select two sub-arrays of equal size from each array and calculate maximum possible OR sum of the two sub-arrays. Note: Let f(x, l, r) is the OR sum of all the elements in the range [l, r] in array x. Examples : Input : A[] = {1, 2, 4, 3, 2} B[] = {2, 3, 3, 12,
5 min read
Pair with maximum GCD from two arrays
Given two arrays of n integers with values of the array being small (values never exceed a small number say 100). Find the pair(x, y) which has maximum gcd. x and y cannot be of the same array. If multiple pairs have the same gcd, then consider the pair which has the maximum sum. Examples: Input : a
15+ min read