C++ code to count number of operations to make two arrays same


Suppose we have two arrays A and B with n number of elements. Consider an operation: Select two indices i and j, then decrease ith element by 1 and increase jth element by 1. Each element of the array must be non-negative after performing an operation. We want to make A and B same. We have to find the sequence of operations to make A and B same. If not possible, return -1.

So, if the input is like A = [1, 2, 3, 4]; B = [3, 1, 2, 4], then the output will be [(1, 0), (2, 0)], because for i = 1 and j = 0 the array will be [2, 1, 3, 4], then for i = 2 and j = 0, it will be [3, 1, 2, 4]

Steps

To solve this, we will follow these steps −

a := 0, b := 0, c := 0
n := size of A
Define an array C of size n and fill with 0
for initialize i := 0, when i < n, update (increase i by 1), do:
   a := a + A[i]
for initialize i := 0, when i < n, update (increase i by 1), do:
   b := b + A[i]
if a is not equal to b, then:
   return -1
Otherwise
   for initialize i := 0, when i < n, update (increase i by 1),
do:
   c := c + |A[i] - B[i]|
   C[i] := A[i] - B[i]
   c := c / 2
   i := 0
   j := 0
   while c is non-zero, decrease c after each iteration, do:
      while C[i] <= 0, do:
         (increase i by 1)
      while C[j] >= 0, do:
         (increase j by 1)
      print i and j
      decrease C[i] and increase C[j] by 1

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(vector<int> A, vector<int> B){
   int a = 0, b = 0, c = 0;
   int n = A.size();
   vector<int> C(n, 0);
   for (int i = 0; i < n; i++)
      a += A[i];
   for (int i = 0; i < n; i++)
      b += A[i];
   if (a != b){
      cout << -1;
      return;
   }
   else{
      for (int i = 0; i < n; i++){
         c += abs(A[i] - B[i]);
         C[i] = A[i] - B[i];
      }
      c = c / 2;
      int i = 0, j = 0;
      while (c--){
         while (C[i] <= 0)
            i++;
         while (C[j] >= 0)
            j++;
         cout << "(" << i << ", " << j << "), ";
         C[i]--, C[j]++;
      }
   }
}
int main(){
   vector<int> A = { 1, 2, 3, 4 };
   vector<int> B = { 3, 1, 2, 4 };
   solve(A, B);
}

Input

{ 1, 2, 3, 4 }, { 3, 1, 2, 4 }

Output

(1, 0), (2, 0),

Updated on: 15-Mar-2022

160 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements