Maximum sum by picking elements from two arrays in order in C++ Program


In this problem, we are given two arrays arr1[] and arr2[], and two numbers N and M.

N gives the number of elements taken from arr1.

M gives the number of elements taken from arr2.

We need to select one of the elements from arr1[i] to arr2[i], for which

makes the sum maximum, but maximum N can be taken from arr1 and M from arr2.

Our task is to create a program to find the maximum sum by picking elements from two arrays in order in C++.

Let’s take an example to understand the problem,

Input

arr1[] = {5, 1, 6, 2, 8, 9}
arr2[] = {8, 4, 7, 9, 1, 3}
M = 3, N = 2

Output

28

Explanation

Here are the elements to be picked,
i = 0, arr1[0] = 5, arr2[0] = 8.Element to be taken 8
i = 1, arr1[1] = 1, arr2[1] = 4.Element to be taken 4
i = 2, arr1[2] = 6, arr2[2] = 7.Element to be taken 6
i = 3, arr1[3] = 2, arr2[3] = 9.Element to be taken 2
i = 4, arr1[4] = 8, arr2[0] = 1.Element to be taken 8

maxSum = 8 + 4 + 6 + 2 + 8 = 28

Solution Approach

To solve the problem one each solution is to find the maximum element of arr1 and arr2, till the element count reaches M or N. And then add all the values to find the sum.

Algorithm

Initialize

maxSum = 0

Step 1

for i −> 0 to n

Step 1.1

if arr1[i] > arr2[i] and M >= 0 −> maxSum += arr1[i].

Step 1.2

else if arr1[i] < arr2[i] and N >= 0 −> maxSum += arr2[i].

Step 1.3

else exit.

Step 3

return maxSum

Example

Program to illustrate the working of our solution,

 Live Demo

#include<iostream>
using namespace std;
int calcMaxSumFromArrays(int arr1[], int arr2[], int N, int M, int size1, int size2) {
   int maxSum = 0;
   for(int i = 0; i < size1; i++){
      if(arr1[i] > arr2[i] && N > 0){
         maxSum += arr1[i];
         N−−;
      }
      else if(arr1[i] <= arr2[i] && M > 0){
         maxSum += arr2[i];
         M−−;
      }
      else if(M > 0){
         maxSum += arr2[i];
         M−−;
      }
      else if(N > 0){
         maxSum += arr1[i];
         N−−;
      }
      else
      return maxSum;
   }
   return maxSum;
}
int main() {
   int arr1[]= {5, 1, 6, 2, 8, 9};
   int arr2[]= {8, 4, 7, 9, 1, 3};
   int N = 3, M = 2;
   int size1 = sizeof(arr1)/sizeof(arr1[0]);
   int size2 = sizeof(arr2)/sizeof(arr2[0]);
   cout<<"The maximum sum by picking elements from two arrays in
   order is "<<calcMaxSumFromArrays(arr1, arr2, N, M, size1, size2);
   return 0;
}

Output

The maximum sum by picking elements from two arrays in order is 28

Updated on: 09-Dec-2020

730 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements