Skip to content
Related Articles

Related Articles

Maximum sum by picking elements from two arrays in order

Improve Article
Save Article
  • Last Updated : 23 Jun, 2022
Improve Article
Save Article

Given two arrays of size N and two integers X and Y indicating the maximum number of elements, one can pick from array A and array B respectively. 
At each ith turn, either A[i] or B[i] can be picked. The task is to make the selection that results in the maximum possible sum. 
Note: It is guaranteed that (X + Y) ≥ N
Examples: 
 

Input: A[] = {1, 2, 3, 4, 5}, B[] = {5, 4, 3, 2, 1}, X = 3, Y = 2 
Output: 21 
i = 0 -> 5 picked 
i = 1 -> 4 picked 
i = 2 -> 3 picked 
i = 3 -> 4 picked 
i = 4 -> 5 picked 
5 + 4 + 3 + 4 + 5 = 21
Input: A[] = {1, 4, 3, 2, 7, 5, 9, 6}, B[] = {1, 2, 3, 6, 5, 4, 9, 8}, X = 4, Y = 4 
Output: 43 
 

 

Approach: Use the greedy approach to select the elements that will result in the maximum sum. The following steps will help in solving this problem: 
 

  • Sort the element pairs according to the absolute difference i.e. |A[i] – B[i]| in decreasing order.
  • Compare A[i] and B[i] value, the one which is greater adds that value to the sum.
  • Decrement X by one if the element is chosen from A[i] else decrement Y by one.
  • Print the sum in the end.

Below is the implementation of the above approach:
 

C++




#include <bits/stdc++.h>
using namespace std;
long long getMaximumSum(vector<int> a, vector<int>b, int n, int x, int y) {
        vector<vector<int> > v;
        long long tsum=0;
        for(int i=0;i<n;i++)
        {
            v.push_back({abs(a[i]-b[i]),a[i],b[i]});
        }
        sort(v.begin(),v.end(),greater<vector<int> >());
        for(int i=0;i<v.size();i++)
        {
            if(v[i][1]>v[i][2] && x>0)
            {
                tsum+=v[i][1];
                x--;
            }
            else if(v[i][1]<v[i][2] && y>0)
            {
                tsum+=v[i][2];
                y--;
            }
            else
            {
                tsum+=min(v[i][2],v[i][1]);  
            }
        }
        return tsum;
}
int main() {
    int x = 3, y = 2;
    vector<int> a= { 1, 2, 3, 4, 5 };
    vector<int> b= { 5, 4, 3, 2, 1 };
    int n = a.size();
    cout<<getMaximumSum(a, b, n, x, y);
    return 0;
}

Java




// Java program to calculate the
// maximum sum obtained by making an
// Optimal selection of elements from two given arrays
 
import java.io.*;
import java.util.*;
import java.lang.*;
 
// User defined Pair class
class Pair {
    int x;
    int y;
 
    // Constructor
    public Pair(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}
 
// Class to define user defined comparator
class Compare {
 
    // Function to reverse the elements of an array
    static void reverseArray(Pair[] arr, int start, int end)
    {
 
        int tempx, tempy;
        while (start < end) {
            tempx = arr[start].x;
            tempy = arr[start].y;
            arr[start].x = arr[end].x;
            arr[start].y = arr[end].y;
            arr[end].x = tempx;
            arr[end].y = tempy;
            start++;
            end--;
        }
    }
 
    // Function to sort the pair according to the
    // absolute differences
    static Pair[] compare(Pair[] arr, int N)
    {
 
        // Comparator to sort the pair according to
        // the absolute differences
        Arrays.sort(arr, new Comparator<Pair>() {
            @Override
            public int compare(Pair p1, Pair p2)
            {
                return (Math.abs(p1.x - p1.y) - Math.abs(p2.x - p2.y));
            }
        });
 
        // To get in descending order
        reverseArray(arr, 0, N - 1);
        return arr;
    }
}
 
// Driver class
class GFG {
 
    // Function to calculate the
    // maximum possible sum obtained by making an
    // optimal selection elements from two given arrays
 
    static int getMaximumSum(int[] A, int[] B, int N,
                                        int X, int Y)
    {
        int num1, num2, sum = 0;
 
        // Making a single pair array having
        // arr[i] element as (Ai, Bi)
        Pair[] arr = new Pair[N];
        for (int i = 0; i < N; i++) {
            arr[i] = new Pair(A[i], B[i]);
        }
 
        // Sorting according to the absolute differences
        // in the decreasing order
        Compare obj = new Compare();
        obj.compare(arr, N);
 
        // Applying Greedy approach to make an optimal
        // selection
        for (int i = 0; i < N; i++) {
            num1 = arr[i].x;
            num2 = arr[i].y;
 
            // If A[i] > B[i]
            if (num1 > num2) {
 
                // If element from A can be picked
                if (X > 0) {
                    sum += num1;
                    X--;
                }
 
                // Insufficient X
                // Make a pick from B
                else if (Y > 0) {
                    sum += num2;
                    Y--;
                }
            }
 
            // If B[i] > A[i]
            else if (num2 > num1 && Y > 0) {
 
                // If element from B can be picked
                if (Y > 0) {
                    sum += num2;
                    Y--;
                }
 
                // Insufficient Y
                // Make a pick from A
                else {
                    sum += num1;
                    X--;
                }
            }
 
            // If A[i] = B[i]
            // Doesn't make a difference so any value
            //  can be picked
            else {
                sum += num1;
                if (X > 0) {
                    X--;
                }
                else if (Y > 0)
                    Y--;
            }
        }
        return sum;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int X = 3, Y = 2;
        int[] A = { 1, 2, 3, 4, 5 };
        int[] B = { 5, 4, 3, 2, 1 };
        int N = A.length;
        System.out.println(getMaximumSum(A, B, N, X, Y));
    }
}

Javascript




<script>
// Javascript program for the above approach
 
function getMaximumSum( a, b, n, x, y) {
        let v=[];
        let tsum=0;
        for(let i=0;i<n;i++)
        {
            v.push([Math.abs(a[i]-b[i]),a[i],b[i]]);
        }
        v.sort();
        v.reverse();
        for(let i=0;i<v.length;i++)
        {
            if(v[i][1]>v[i][2] && x>0)
            {
                tsum+=v[i][1];
                x--;
            }
            else if(v[i][1]<v[i][2] && y>0)
            {
                tsum+=v[i][2];
                y--;
            }
            else
            {
                tsum+=Math.min(v[i][2],v[i][1]);
            }
        }
        return tsum;
}
 
// Driver Code
    let x = 3;
    let y = 2;
    let a= [ 1, 2, 3, 4, 5 ];
    let b= [ 5, 4, 3, 2, 1 ];
    let n = a.length;
    document.write(getMaximumSum(a, b, n, x, y));
 
// This program is contributed by Pushpesh Raj.
</script>

Output: 

21

 

Time Complexity: O(n*log(n))
Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!