CAKEWALK

# PREREQUISITES:

Arrays and Mathematics

# PROBLEM:

Given an array of integers, find a value to be inserted at the beginning such that sum of elements at odd and even indices becomes equal.

# QUICK EXPLANATION:

Assume that value added at beginning is V, and sum of odd index elements be sumOdd, even index elements be sumEven, then to maintain equal sums, V = sumEven - sumOdd.

# EXPLANATION:

After adding an element V at the beginning of the array, the elements present at odd indices move to even indices and vice versa.

So, if you have calculated the odd and even index element sums to be sumOdd and sumEven respectively, after adding V they interchange.

Also, since V is at 0^{th} index (even), it will now be counted in sumOdd. (original sumEven)

Thus,

V + sumOdd = sumEven

And giving the answer to be:

V = sumEven - sumOdd.

# SOLUTIONS:

``````#include <bits/stdc++.h>
using namespace std;

int main () {
int t;
cin >> t;

while (t--) {
int n;
cin >> n;

vector<int> arr(n);
int odd_sum = 0;
int even_sum = 0;
for (int i = 0; i < n; ++i) {
cin >> arr[i];
if (i & 1) {
odd_sum += arr[i];
} else {
even_sum += arr[i];
}
}
cout << even_sum - odd_sum << endl;

}
return 0;
}
``````