Untitled

mail@pastecode.io avatar
unknown
c_cpp
6 months ago
1.5 kB
1
Indexable
Never
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

long long max_difference(int n, vector<long long>& powers) {
    vector<long long> prefixSum(n, 0), suffixSum(n, 0);
    
    // Calculate prefix and suffix sums
    prefixSum[0] = powers[0];
    for (int i = 1; i < n; ++i) {
        prefixSum[i] = prefixSum[i - 1] + powers[i];
    }

    suffixSum[n - 1] = powers[n - 1];
    for (int i = n - 2; i >= 0; --i) {
        suffixSum[i] = suffixSum[i + 1] + powers[i];
    }

    long long left = 0, right = n - 1, turn = 1, difference = 0;

    while (left <= right) {
        if (turn % 2 == 1) {  // Iron Man's turn
            if (prefixSum[left] < suffixSum[right]) {
                difference += suffixSum[right];
                right--;
            } else {
                difference += prefixSum[left];
                left++;
            }
        } else {  // Captain America's turn
            if (prefixSum[left] < suffixSum[right]) {
                difference -= prefixSum[left];
                left++;
            } else {
                difference -= suffixSum[right];
                right--;
            }
        }
        turn++;
    }

    return abs(difference);
}

int main() {
    int n;
    cin >> n;
    
    vector<long long> powers(n);
    for(int i = 0; i < n; i++) {
        cin >> powers[i];
    }
    
    cout << max_difference(n, powers) << endl;
    
    return 0;
}