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;

void foo(T)(BinaryHeap!(T) q) {
    writeln(typeid(q));
}

// 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.popFront();
        }
        sum[i] = s;
    }
    return sum;
}

// sum[p] = 0..p の中から n 個の要素を選び、最大の和を格納
long[] calcLeft(int[] xs) {
    long[] sum = new long[xs.length];
    long s = 0;
    int d = cast(int)xs.length / 3;
    auto q = new BinaryHeap!(Array!long, "a > b"); // 小さい順から取り出せる
    for (int i = 0; i < d * 2; i++) {
        q.insert(xs[i]);
        s += xs[i];
        if (q.length > d) {
            s -= q.front;
            q.removeFront;
        }
        sum[i] = s;
    }
    return sum;
}

// sum[p] = p..$ の中から n 個の要素を選び、最小の和を格納
long[] calcRight(int[] xs) {
    long[] sum = new long[xs.length];
    long s = 0;
    int d = cast(int)xs.length / 3;
    auto q = new BinaryHeap!(Array!long, "a < b"); // 大きい順から取り出す
    for (int i = cast(int)xs.length-1; i >= d; i--) {
        q.insert(xs[i]);
        s += xs[i];
        if (q.length > d) {
            s -= q.front;
            q.popFront;
        }
        sum[i] = s;
    }
    return sum;
}

long calc(int[] xs) {
    /*
    auto lefts  = calcLeft(xs);
    auto rights = calcRight(xs);

    auto n = xs.length;
    auto d = cast(int)xs.length / 3;
    long ans = long.min;
    for (int i = d - 1; i < 2 * d; i++) {
        long diff = lefts[i] - rights[i + 1];
        ans = max(ans, diff);
    }
    return ans;
    */

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

//    writeln(lsum);
//    writeln(rsum);

    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);
}
