0% found this document useful (0 votes)
2 views2 pages

Take It Part

The provided C++ code defines a function to calculate the minimum absolute difference between two players' sums based on their choices from an array. It computes total sums, prefix sums, and sums of even and odd indexed elements, then evaluates three cases of player choices to determine the minimum difference. The main function handles multiple test cases, reading input values and invoking the solve function for each case.

Uploaded by

Tanu Dahiya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Take It Part

The provided C++ code defines a function to calculate the minimum absolute difference between two players' sums based on their choices from an array. It computes total sums, prefix sums, and sums of even and odd indexed elements, then evaluates three cases of player choices to determine the minimum difference. The main function handles multiple test cases, reading input values and invoking the solve function for each case.

Uploaded by

Tanu Dahiya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Take it part :-

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

long long solve(int N, vector<int> A) {


// Calculate total sum, prefix sums, and even/odd indexed sums.
long long total = 0;
long long even_sum = 0, odd_sum = 0;
vector<long long> prefix(N + 1, 0); // prefix[0] = 0, prefix[i] = sum of A[0]...A[i-1]

for (int i = 0; i < N; i++) {


total += A[i];
prefix[i + 1] = prefix[i] + A[i];
if (i % 2 == 0)
even_sum += A[i];
else
odd_sum += A[i];
}

// Case 1: Both players choose the same side.


long long diff_same = llabs(even_sum - odd_sum);

// Case 2: Alex picks from left and Bob picks from right.
int k_lr = (N + 1) / 2; // Alex gets ceil(N/2) moves.
long long diff_lr = llabs(2 * prefix[k_lr] - total);

// Case 3: Alex picks from right and Bob picks from left.
int k_rl = N / 2; // Bob gets floor(N/2) moves.
long long diff_rl = llabs(total - 2 * prefix[k_rl]);

// Return the minimum absolute difference.


return min({diff_same, diff_lr, diff_rl});
}

int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);

int T;
cin >> T;
while (T--) {
int N;
cin >> N;
vector<int> A(N);
for (int i = 0; i < N; i++) {
cin >> A[i];
}
cout << solve(N, A) << "\n";
}

return 0;
}

You might also like