在C ++中生成相同总和的对的最大数量
给我们一个整数数组。目的是在数组中找到最大对数,相加后将产生相同的总和。我们必须找到此类对的最大数量。
输入值
Arr[]= { 1,2,3,4,2 }输出结果
Maximum count of pairs with same sum : 3
说明-数字对的总和-
{1,2}, {1,2} Sum:3
{1,3},{2,2} Sum:4
{1,4},{2,3},{3,2} Sum:5
{2,4} Sum:6
{3,4} Sum:7
Maximum count of pairs with same sum is 3 ( for sum = 5 )输入值
Arr[]= { 5,3,6,1 }输出结果
Maximum count of pairs with same sum : 1
说明-数字对的总和-
{5,3} Sum:8
{5,6} Sum:11
{5,1} Sum:6
{3,6} Sum:9
{3,1} Sum:4
{6,1} Sum:7
Maximum count of pairs with the same sum is 1.以下程序中使用的方法如下
整数数组Arr[]用于存储整数。
整数“大小”存储数组的长度。
函数countEqualSum(intarr[],intn)接受一个数组,其大小作为输入,并返回生成相同总和的对的最大数量。
首先,我们将使用“求和”数组来存储唯一和的频率。
在总和的每个索引处,该元素的增量计数。
数组总和的每个索引是一对元素的总和。
通过搜索数组和内的max元素并存储在maxC中,找到最大的此类计数。
返回maxC作为结果
示例
#include <bits/stdc++.h>
using namespace std;
// Function to return the maximum
// count of pairs with equal sum
int countEqualSum(int arr[], int n){
int sum[20]={0};
int maxC = 0;
// Store counts of sum of all pairs
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++){
sum[ arr[i]+arr[j] ]++;
}
for(int i=0;i<20;i++)
if(sum[i]>maxC)
maxC=sum[i];
return maxC;
}
int main(){
int Arr[] = { 1,2,3,4,2 };
int size = 5;
cout <<”Maximum count of pairs which generate the same sum”
<< countEqualSum(Arr, size);
return 0;
}输出结果
Maximum count of pairs which generate the same sum : 3