import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

T read(T)() { return readln.chomp.to!T; }
T[] reads(T)() { return readln.split.to!(T[]); }
alias readint = read!int;
alias readints = reads!int;

// sum[p] = xs[0..p] の中から値の大きい(小さい)順の N 個の総和
long[] calcBestN(int[] xs, bool function(long, long) cmp) {
    assert(xs.length % 3 == 0);

    auto sum = new long[xs.length];
    auto q = new BinaryHeap!(Array!long, cmp);
    long s = 0;
    int N = cast(int)xs.length / 3;
    for (int i = 0; i < xs.length; i++) {
        q.insert(xs[i]);
        s += xs[i];
        if (q.length > N) {
            s -= q.front;
            q.removeFront();
        }
        sum[i] = s;
    }
    return sum;
}

long calc(int[] xs) {
    auto lsum = calcBestN(xs, (a, b) => a > b);

    auto ys = xs.dup;
    ys.reverse();
    auto rsum = calcBestN(ys, (a, b) => a < b);
    rsum.reverse();

    long ans = long.min;
    int N = cast(int)xs.length / 3;
    for (int i = N-1; i < 2 * N; i++) {
        // i までが左側に属する。i+1 以降は右側
        long diff = lsum[i] - rsum[i + 1];
        ans = max(ans, diff);
    }
    return ans;
}

void main() {
    readint;
    auto xs = readints;
    auto ans = calc(xs);
    writeln(ans);
}
