Find a pair of elements swapping which makes sum of two arrays same in C++

C++Server Side ProgrammingProgramming

Consider we have two arrays with different number of elements. We have to find a pair of elements (x, y), where x is present in the first array, and y is present at the second array. The pair will be chosen such that after swapping the elements between these two arrays, the sum of these two arrays will be same.

Suppose first array A is holding [4, 1, 2, 2, 1, 1] and B is holding [3, 3, 6, 3], now the sum of A is 11 and sum of B is 15, we will take a pair like (1, 3), if we swap these values between these two arrays, then the sum will be: [4, 3, 2, 2, 1, 1] = 13, [1, 3, 6, 3] = 13, they are same.

To solve this we will iterate through the array and check all pairs of values, compare new sums or look for another pair with that difference.

Example

 Live Demo

#include<iostream>
using namespace std;
int arraySum(int arr[], int n) {
   int sum = 0;
   for (int i = 0; i < n; i++)
   sum += arr[i];
   return sum;
}
void getPair(int A[], int n, int B[], int m) {
   int sum_first = arraySum(A, n);
   int sum_second = arraySum(B, m);
   int newsum_first, newsum_second, first, second;
   for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
         newsum_first = sum_first - A[i] + B[j];
         newsum_second = sum_second - B[j] + A[i];
         if (newsum_first == newsum_second) {
            first = A[i];
            second = B[j];
         }
      }
   }
   cout << "(" << first << ", " << second << ")";
}
int main() {
   int A[] = { 4, 1, 2, 2, 1, 1 };
   int n = sizeof(A) / sizeof(A[0]);
   int B[] = { 3, 3, 6, 3 };
   int m = sizeof(B) / sizeof(B[0]);
   getPair(A, n, B, m);
}

Output

(1, 3)
raja
Published on 24-Oct-2019 16:14:48
Advertisements