Maximum count of pairs which generate the same sum in C++


We are given with an array of integers. The goal is to find the maximum number of pairs in the array that when added produce the same sum. We have to find the maximum count of such pairs.

Input

Arr[]= { 1,2,3,4,2 }

Output

Maximum count of pairs with same sum : 3

Explanation − Sum of pairs of numbers −

{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 )

Input

Arr[]= { 5,3,6,1 }

Output

Maximum count of pairs with same sum : 1

Explanation − Sum of pairs of numbers −

{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.

Approach used in the below program is as follows

  • The integer array Arr[] is used to store the integers.

  • Integer ‘size’ stores the length of the array.

  • Function countEqualSum( int arr[], int n) takes an array , its size as input and returns the maximum count of pairs which generate the same sum.

  • First of all we will take ‘sum’ array to store the frequency of unique sums.

  • At each index of sum, increment count of that element.

  • Each index of array sum is the sum of a pair of elements.

  • Find maximum such count by search for max element inside array sum and store in maxC.

  • Return maxC as result

Example

 Live Demo

#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;
}

Output

Maximum count of pairs which generate the same sum : 3

Updated on: 28-Jul-2020

542 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements