Maximize the sum of X+Y elements by picking X and Y elements from 1st and 2nd array in C++


For the given two arrays each of size N, the task is to find the maximum sum by choosing X elements from array 1 and Y elements from array 2.

Let’s now understand what we have to do using an example −

Input 

arr1 = {1,2,3,4,5} ; X=2
arr2 = {1,3,5,2,7}; Y=3

Output 

Maximum sum here is : 24

Explanation − We are selecting 2 number(s) from arr1 and 3 from arr2. Largest 2 of arr1 are 4,5 and largest 3 of arr2 are 3,5,7. Total sum of these 5 elements is 24 which is maximum as per the requirement.

Input 

arr1 = {10,13,16,14}; X=1
arr2 = {4,1,2,1}; Y=2

Output 

Maximum sum here is : 22

Explanation − We are selecting 1 number(s) from arr1 and 2 from arr2. Largest of arr1 is 16 and the largest 2 of arr2 are 4,2. Total sum of these 5 elements is 22 which is maximum as per the requirement.

Approach used in the below program as follows

  • Take input arrays arr1[] and arr2[] and values for X and Y..

  • Sort the two arrays in ascending order.

  • Take last X elements from arr1 and Y from arr2 as these will be the highest.

  • At last we return the sum of elements selected in step 3 as it will be the maximum.

  • Note: sort(arr[],int) is assumed to return the sorted array.

Example

#include <iostream>
using namespace std;
int max_sum(int arr1[],int arr2[], int length,int X,int Y){
   //for sorting the array
   sort(arr1,length);
   sort(arr2,length);
   int sum=0;
   int i;
   //adding last X elements from arr1 and last Y elements from arr2
   for(i=0;i<X;i++){
      sum+=arr1[length-i-1];
   }
   for(i=0;i<Y;i++){
      sum+=arr2[length-i-1];
   }
   return(sum);
}
// Driver program
int main(){
   int arr1[]={1,1,1,3,7};
   int arr2[]={1,1,2,3,5};
   int x=3,y=2;
   printf( "Maximized sum of X+Y elements by picking X and Y elements from 1st and 2nd array is %d",max_sum(arr1,arr2,5,x,y));
   return 0;
}

Output

If we run the above code we will get the following output −

Maximized sum of X+Y elements by picking X and Y elements from 1st and 2nd array is 19

Updated on: 14-Aug-2020

132 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements