Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
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 = 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 −
#includeusing namespace std; void solve(vector A, vector B){ int a = 0, b = 0, c = 0; int n = A.size(); vector C(n, 0); for (int i = 0; i = 0) j++; cout A = { 1, 2, 3, 4 }; vector B = { 3, 1, 2, 4 }; solve(A, B); }
Input
{ 1, 2, 3, 4 }, { 3, 1, 2, 4 }
Output
(1, 0), (2, 0),
