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[]用于存储整数。
整数“size”存储数组的长度。
函数countEqualSum( int arr[], int n)接收一个数组及其大小作为输入,并返回生成相同和的数对的最大计数。
首先,我们将使用“sum”数组来存储唯一和的频率。
在sum的每个索引处,递增该元素的计数。
数组sum的每个索引都是一对元素的和。
通过搜索sum数组中的最大元素并将其存储在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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP