- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find a pair of elements swapping which makes sum of two arrays same in C++
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
#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)
Advertisements