通过在C ++程序中依次从两个数组中选取元素来获得最大和
在这个问题中,我们得到了两个数组arr1[]和arr2[],以及两个数字N和M。
N给出从arr1中获取的元素数。
M给出了从arr2中获取的元素数。
我们需要从arr1[i]到arr2[i]中选择一个元素,为此
使总和最大,但最大N可以从arr1取,M可以从arr2取。
我们的任务是创建一个程序,通过在C++中依次从两个数组中选取元素来找到最大和。
让我们举个例子来了解这个问题,
输入项
arr1[] = {5, 1, 6, 2, 8, 9} arr2[] = {8, 4, 7, 9, 1, 3} M = 3, N = 2
输出结果
28
说明
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
解决方法
解决该问题的一种方法是找到arr1和arr2的最大元素,直到元素数达到M或N。然后将所有值相加以求和。
算法
初始化-
maxSum = 0
第1步-
for i −> 0 to n
步骤1.1-
if arr1[i] > arr2[i] and M >= 0 −> maxSum += arr1[i].
步骤1.2-
else if arr1[i] < arr2[i] and N >= 0 −> maxSum += arr2[i].
步骤1.3-
else exit.
第3步-
return maxSum
示例
该程序说明了我们解决方案的工作原理,
#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; }
输出结果
The maximum sum by picking elements from two arrays in order is 28