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