Problem:
 Score : 500 points    Problem Statement Let N be a positive integer.  There is a numerical sequence of length 3N , a = (a_1, a_2, ..., a_{3N}) .
Snuke is constructing a new sequence of length 2N , a' , by removing exactly N elements from a without changing the order of the remaining elements.
Here, the score of a' is defined as follows: ( the sum of the elements in the first half of a') - ( the sum of the elements in the second half of a') .  Find the maximum possible score of a' .      Constraints  1 ≤ N ≤ 10^5  a_i is an integer.  1 ≤ a_i ≤ 10^9       Partial Score  In the test set worth 300 points, N ≤ 1000 .         Input Input is given from Standard Input in the following format:  N  a_1  a_2  ...  a_{3N}       Output Print the maximum possible score of a' .        Sample Input 1 2
3 1 4 1 5 9      Sample Output 1 1  When a_2 and a_6 are removed, a' will be (3, 4, 1, 5) , which has a score of (3 + 4) - (1 + 5) = 1 .       Sample Input 2 1
1 2 3      Sample Output 2 -1  For example, when a_1 are removed, a' will be (2, 3) , which has a score of 2 - 3 = -1 .       Sample Input 3 3
8 2 2 7 4 6 5 3 8      Sample Output 3 5  For example, when a_2 , a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3) , which has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5 .

Solution (Python):
N=int(input())
A=list(map(int,input().split()))
h1=A[:N]
L=[0 for i in range(N+1)]
L[0]=sum(h1)
sum1=sum(h1)
import heapq
heapq.heapify(h1)
for i in range(N):
  heapq.heappush(h1,A[N+i])
  a=heapq.heappop(h1)
  sum1=sum1+A[N+i]-a
  L[i+1]=sum1
h=A[2*N:]
h2=[-i for i in h]
R=[0 for i in range(N+1)]
R[N]=-sum(h2)
sum2=-sum(h2)
heapq.heapify(h2)
for i in range(N):
  heapq.heappush(h2,-A[2*N-1-i])
  a=heapq.heappop(h2)
  sum2=sum2+A[2*N-1-i]+a
  R[N-i-1]=sum2
import math
ans=-math.inf
for i in range(N+1):
  ans=max(ans,L[i]-R[i])
print(ans)

Solution (Python):
import heapq
N=int(input())
A=list(map(int, input().split()))
A_rev = [-x for x in A[::-1]] 
left, right = A[:N], A_rev[:N]
sum_left_list, sum_right_list = [0]*(N+1), [0]*(N+1)
sum_left, sum_right = sum(left), sum(right)
sum_left_list[0], sum_right_list[0]=sum_left, sum_right
heapq.heapify(left)
heapq.heapify(right)

for k in range(N, 2*N):
	val=A[k]
	heapq.heappush(left, val)
	min_val = heapq.heappop(left)
	sum_left += val
	sum_left -= min_val
	sum_left_list[k-N+1] = sum_left


for k in range(N, 2*N):
	val = A_rev[k]
	heapq.heappush(right, val)
	min_val = heapq.heappop(right)
	sum_right += val
	sum_right -= min_val
	sum_right_list[k-N+1] = sum_right
sum_right_list=sum_right_list[::-1]

ans=-float("inf")
for i in range(N+1):
	ans=max(ans, sum_left_list[i]+sum_right_list[i])
print(ans)

Solution (Python):

import heapq
N=int(input())
A=list(map(int, input().split()))

left, right = A[:N], [-1 * i for i in A[2*N:]]
sum_left, sum_right = sum(left), sum(right)

results = [0] * (N+1)
results[0] = sum_left
results[N] = sum_right

heapq.heapify(left)
heapq.heapify(right)

for i in range(N, 2*N):
    v = A[i]
    p = heapq.heappushpop(left, v)
    sum_left += v - p
    results[i-N+1] += sum_left
    
for i in range(2*N-1, N-1, -1):
    v = -1 * A[i]
    p = heapq.heappushpop(right, v)
    sum_right += v - p
    results[i-N] += sum_right
print(max(results))

Solution (Python):
import heapq

n=int(input())
*a,=map(int,input().split())

lq=[]
lsum=0
for i in range(n):
    heapq.heappush(lq,a[i])
    lsum+=a[i]

l=[0]*(3*n)
l[n-1]=lsum
for i in range(n,2*n):
    lsum+=a[i]
    heapq.heappush(lq,a[i])
    lsum-=heapq.heappop(lq)
    l[i]=lsum

rq=[]
rsum=0
for i in range(3*n-1,2*n-1,-1):
    heapq.heappush(rq,-a[i])
    rsum+=a[i]

r=[0]*(3*n)
r[2*n]=rsum
for i in range(2*n-1,n-1,-1):
    rsum+=a[i]
    heapq.heappush(rq,-a[i])
    rsum+=heapq.heappop(rq)
    r[i]=rsum

ans=-10**15

for i in range(n-1,2*n):
    ans=max(ans,l[i]-r[i+1])

print(ans)

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]



def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





N = I()
A = IL()

mae = A[:N]
heapq.heapify(mae)
mae_score = [sum(mae)]

for i in range(N):
  a = A[i+N]
  if a > mae[0]:
    mae_score.append(mae_score[-1]+a-heapq.heappop(mae))
    heapq.heappush(mae,a)
  else:
    mae_score.append(mae_score[-1])

ushiro = [-i for i in A[2*N:]]
heapq.heapify(ushiro)
ushiro_score = [sum(ushiro)]

for i in range(N):
  a = -A[2*N-1-i]
  if a > ushiro[0]:
    ushiro_score.append(ushiro_score[-1]+a-heapq.heappop(ushiro))
    heapq.heappush(ushiro,a)
  else:
    ushiro_score.append(ushiro_score[-1])

ans = -INF
for i in range(N+1):
  ans = max(ans,mae_score[i]+ushiro_score[N-i])

print(ans)

Solution (Python):
with open(0) as f:
    N, *a = map(int, f.read().split())
F = [x for x in a[:N]] 
C = [x for x in a[N:2*N]] 
B = [-x for x in a[2*N:]] 
import heapq as hq

hq.heapify(F)
hq.heapify(B)








from copy import deepcopy
memoF = [0] * (N+1) 
memoF[0] = sum(F)
memoB = [0] * (N+1) 
memoB[N] = sum(B)
for i in range(N):
    if C[i] > F[0]:
        memoF[i+1] = memoF[i] + C[i] - hq.heapreplace(F, C[i])
    else:
        memoF[i+1] = memoF[i]

    if -C[N-1-i] > B[0]:
        memoB[N-1-i] = memoB[N-i] - C[N-1-i] - hq.heapreplace(B, -C[N-1-i])
    else:
        memoB[N-1-i] = memoB[N-i]

Scores = [memoF[i]+memoB[i] for i in range(N+1)]
ans = max(Scores)
print(ans)

Solution (Python):
def main():
    n = int(input())
    a = list(map(int, input().split()))

    from heapq import heapify, heappushpop

    
    fh = []
    l = a[:n]
    fh.append(sum(l))
    heapify(l)
    for i in a[n:2*n]:
        if l[0] < i:
            fh.append(fh[-1] + i - heappushpop(l, i))
        else:
            fh.append(fh[-1])

    
    lh = []
    l = [-i for i in a[2*n:]]
    lh.append(sum(l))
    heapify(l)
    for i in a[2*n-1:n-1:-1]:
        if l[0] < -i:
            lh.append(lh[-1] - i - heappushpop(l, -i))
        else:
            lh.append(lh[-1])

    ans = fh[0] + lh[n]
    for i in range(1, n+1):
        if ans < fh[i] + lh[n-i]:
            ans = fh[i] + lh[n-i]

    print(ans)

main()

Solution (Python):
def main():
    n = int(input())
    a = list(map(int, input().split()))

    from heapq import heapify, heappushpop

    
    fh = []
    l = a[:n]
    fh.append(sum(l))
    heapify(l)
    for i in a[n:2*n]:
        if l[0] < i:
            fh.append(fh[-1] + i - heappushpop(l, i))
        else:
            fh.append(fh[-1])

    
    lh = []
    l = [-i for i in a[2*n:]]
    lh.append(sum(l))
    heapify(l)
    for i in a[2*n-1:n-1:-1]:
        if l[0] < -i:
            lh.append(lh[-1] - i - heappushpop(l, -i))
        else:
            lh.append(lh[-1])

    ans = fh[0] + lh[n]
    for i in range(1, n+1):
        if ans < fh[i] + lh[n-i]:
            ans = fh[i] + lh[n-i]

    print(ans)

main()

Solution (Python):
from heapq import heappop, heappush, heapify

n = int(input())
al = list(map(int, input().split()))

ll = al[0:n]
cl = al[n:2*n]
rl = al[2*n:3*n]
rl = list(map(lambda x: -x, rl))


heapify(ll)
heapify(rl)

ll_vals = []
ll_vals.append(sum(ll))
c_sum = sum(ll)
c_max = c_sum
for i in range(n):
    poped = heappop(ll)
    c_sum -= poped
    heappush(ll,cl[i])
    c_sum += cl[i]
    c_max = max(c_max, c_sum)
    ll_vals.append(c_max)


rl_vals = []
rl_vals.append(-sum(rl))
c_sum = -sum(rl)
c_min = c_sum
for i in range(n):
    poped = -heappop(rl)
    c_sum -= poped
    heappush(rl,-cl[n-1-i])
    c_sum += cl[n-1-i]
    c_min = min(c_min, c_sum)
    rl_vals.append(c_min)


ans = -1*(10**18)
for i in range(n+1):
    v = ll_vals[i] - rl_vals[n-i]
    ans = max(ans,v)

print(ans)

Solution (Python):
from heapq import *
N = int(input())
A = list(map(int,input().split()))
L,C,R = A[:N],A[N:2*N],A[2*N:]
F = [sum(L)]
heapify(L)

for c in C:
  F.append(F[-1]+c-heappushpop(L,c))

R = [-r for r in R]
B = [sum(R)]
heapify(R)

for c in reversed(C):
  B.append(B[-1]-c-heappushpop(R,-c))

print(max(f+b for f,b in zip(F,reversed(B))))

Solution (Python):
from heapq import heappop,heappush
n=int(input())
a=list(map(int,input().split()))
p=sum(a[2*n:])
right_min=[p]
hq=[]
for i in range(2*n,2*n+n):
	heappush(hq,-a[i])
for i in range(n):
	p+=a[-n-i-1]
	heappush(hq,-a[-n-i-1])
	p+=heappop(hq)
	right_min.append(p)
l=sum(a[:n])
hq=[]
for i in range(n):
	heappush(hq,a[i])
right_min.reverse()
ans=l-right_min[0]
for i in range(n):
	l+=a[n+i]
	heappush(hq,a[n+i])
	l-=heappop(hq)
	ans=max(ans,l-right_min[i+1])
print(ans)

Solution (Python):
import  heapq

N = int(input())
a = list(map(int, input().split()))
c_que = list(map(lambda x:x*(-1), a[2*N:]))
a_que = a[:N]

a_sum = sum(a_que)
c_sum = -sum(c_que)

heapq.heapify(a_que)
heapq.heapify(c_que)

ans = -(10**15)

score = [[0, 0] for _ in range(N+1)]
score[0][0] = a_sum
score[N][1] = c_sum

for i in range(N):
    heapq.heappush(a_que, a[N+i])
    heapq.heappush(c_que, -a[2*N-1-i])
    
    a_sum = a_sum + a[N+i] - heapq.heappop(a_que)
    c_sum = c_sum + a[2*N-1-i] + heapq.heappop(c_que)
    
    score[i+1][0] = a_sum
    score[N-1-i][1] = c_sum
    
for i in range(N+1):
    ans = max(ans, score[i][0]-score[i][1])
print(ans)

Solution (Python):
import sys
from heapq import *
input = sys.stdin.readline


def main():
    n = int(input())
    a = list(map(int, input().split()))

    af = a[:n]
    ab = [-v for v in a[2*n:]]
    af_sum = sum(af)
    ab_sum = -sum(ab)

    heapify(af)
    heapify(ab)
    judge = [0]*(n+1)
    judge[0] += af_sum
    judge[n] -= ab_sum
    
    for i in range(n):
        if a[n+i] > af[0]:
            af_sum -= heappop(af)
            heappush(af, a[n+i])
            af_sum += a[n+i]
        judge[i+1] += af_sum
        
        if -a[2*n-1-i] > ab[0]:
            ab_sum += heappop(ab)
            heappush(ab, -a[2*n-1-i])
            ab_sum += a[2*n-1-i]
        judge[n-1-i] -= ab_sum
    

    ans = max(judge)
    print(ans)

    
if __name__ == "__main__":
    main()

Solution (Python):
import sys
from heapq import *
input = sys.stdin.readline


def main():
    n = int(input())
    a = list(map(int, input().split()))

    af = a[:n]
    ab = [-v for v in a[2*n:]]
    af_sum = sum(af)
    ab_sum = -sum(ab)

    heapify(af)
    heapify(ab)
    judge = [0]*(n+1)
    judge[0] += af_sum
    judge[n] -= ab_sum
    
    for i in range(n):
        if a[n+i] > af[0]:
            af_sum -= heappop(af)
            heappush(af, a[n+i])
            af_sum += a[n+i]
        judge[i+1] += af_sum
        
        if -a[2*n-1-i] > ab[0]:
            ab_sum += heappop(ab)
            heappush(ab, -a[2*n-1-i])
            ab_sum += a[2*n-1-i]
        judge[n-1-i] -= ab_sum
    

    ans = max(judge)
    print(ans)

    
if __name__ == "__main__":
    main()

Solution (Python):
import sys
from itertools import accumulate
from heapq import heappush, heappop
def input(): return sys.stdin.readline().strip()


def main():
    N = int(input())
    A = [0] + list(map(int, input().split()))
    S = list(accumulate(A))

    
    small = [0] * (N + 1)
    q = []
    for i in range(1, N + 1): heappush(q, A[i])
    for i in range(1, N + 1):
        heappush(q, A[N + i])
        v = heappop(q)
        small[i] = small[i - 1] + v

    
    large = [0] * (N + 1)
    q = []
    for i in range(2 * N + 1, 3 * N + 1): heappush(q, -A[i])
    for i in range(1, N + 1):
        heappush(q, -A[2 * N + 1 - i])
        v = -heappop(q)
        large[i] = large[i - 1] + v

    ans = -10**18
    for i in range(N, 2 * N + 1):
        """
        A[1],A[2],...,A[i]から小さい順に(i - N)個除いたものが前半
        A[i+1],A[i+2],...,A[3N]から大きい順に(2N - i)個除いたものが後半
        """
        pre = S[i] - small[i - N]
        post = (S[-1] - S[i]) - large[2 * N - i]
        ans = max(ans, pre - post)
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
from heapq import heapify, heappushpop

def abc062_d():
    n = int(input())
    A = list(map(int, input().split()))

    front = A[:n]
    fsum = [0] * (3*n)
    fsum[n-1] = sum(front)
    heapify(front)
    for i in range(n, 2*n):
        fmin = heappushpop(front, A[i])
        fsum[i] = fsum[i-1] + A[i] - fmin

    back = [-1*a for a in A[2*n:]]
    bsum = [0] * (3*n)
    bsum[2*n] = -1 * sum(back)
    heapify(back)
    for i in range(2*n-1, n-1, -1):
        bmax = -1 * heappushpop(back, -1*A[i])
        bsum[i] = bsum[i+1] + A[i] - bmax

    ans = -10**18
    for i in range(n-1, 2*n):
        ans = max(ans, fsum[i] - bsum[i+1])
    print(ans)

if __name__ == '__main__':
    abc062_d()

Solution (Python):
import heapq

n = int(input())
a = list(map(int, input().split()))
score = [[0, 0] for _ in range(n + 1)]
h1 = a[0 : n]
h2 = [-a[2 * n + i] for i in range(n)]
maxscore = sum(h1)
minscore = -sum(h2)
heapq.heapify(h1)
heapq.heapify(h2)
score[0][0] = maxscore
score[n][1] = minscore
for i in range(n):
    heapq.heappush(h1, a[n + i])
    heapq.heappush(h2, -a[2 * n - 1 - i])
    maxscore = maxscore + a[n + i] - heapq.heappop(h1)
    minscore = minscore + a[2 * n - 1 - i] + heapq.heappop(h2)
    score[i + 1][0] = maxscore
    score[n - 1 - i][1] = minscore
ans = -pow(10, 15)
for i in range(n + 1):
    ans = max(ans, score[i][0] - score[i][1])
print(ans)

Solution (Python):
import heapq

N = int(input())
A = list(map(int, input().split()))

L = A[:N]
heapq.heapify(L)
Lmax = [0] * (N + 1)
Lsum = sum(L)
Lmax[0] = Lsum
for i in range(N, 2 * N):
    m = heapq.heappushpop(L, A[i])
    Lsum += A[i] - m
    Lmax[i - N + 1] = Lsum

R = [-x for x in A[2 * N:]]
heapq.heapify(R)
Rmin = [0] * (N + 1)
Rsum = -sum(R)
Rmin[N] = Rsum
for i in range(2 * N - 1, N - 1, -1):
    M = -heapq.heappushpop(R, -A[i])
    Rsum -= M - A[i]
    Rmin[i - N] = Rsum

print(max(Lmax[i] - Rmin[i] for i in range(N + 1)))

Solution (Python):




from heapq import heapify,heappush,heappop

n=int(input())
a=list(map(int,input().split()))

a1=a[0:n]
a_m=a[n:2*n]
a2=[ -x for x in a[2*n:3*n] ] 

a1_sums=[sum(a1)]
a2_sums=[sum(a2)]
heapify(a1)
heapify(a2)


for aa in a_m:
  heappush(a1,aa)
  p=heappop(a1)
  a1_sums.append(a1_sums[-1]+aa-p)


a_m.reverse()
for aa in a_m:
  heappush(a2,-aa)
  p=heappop(a2)
  a2_sums.append(a2_sums[-1]-aa-p)

max_val=-float("inf")
for i in range(0,n+1):
  max_val=max(max_val,a1_sums[i]+a2_sums[n-i])

print(max_val)

Solution (Python):
import heapq
n = int(input())
A = list(map(int,input().split()))
L = A[:n]
R = A[2*n:]
R = list(map(lambda x:-x,R))
sum_l = [sum(L)]
sum_r = [sum(R)]
heapq.heapify(L)
heapq.heapify(R)
for i in range(n):
    elem = A[n+i]
    heapq.heappush(L,elem)
    sum_l.append(sum_l[-1] + elem -heapq.heappop(L))
for i in range(n):
    elem = -A[2*n-1-i]
    heapq.heappush(R,elem)
    sum_r.append(sum_r[-1] + elem -heapq.heappop(R))
ans = -float('inf')
sum_r = sum_r[::-1]
for i in range(len(sum_l)):
    ans = max(ans,sum_l[i] + sum_r[i])
print(ans)

Solution (Python):
import sys
from heapq import heapify,heappushpop

def main():
    rl=sys.stdin.readline
    n=int(rl().strip())
    a=list(map(int,rl().strip().split()))
    b=[-x for x in a]
    b.reverse()
    fl=a[:n]
    fs=sum(fl)
    ll=b[:n]
    ls=sum(ll)
    fdl=[0]*(n+1)
    ldl=[0]*(n+1)
    heapify(fl)
    heapify(ll)
    for i in range(1,n+1):
        fmn=heappushpop(fl,a[n+i-1])
        lmn=heappushpop(ll,b[n+i-1])
        fdl[i]=fdl[i-1]+a[n+i-1]-fmn
        ldl[i]=ldl[i-1]+b[n+i-1]-lmn
    ldl.reverse()
    dif=max([x+y for x,y in zip(fdl,ldl)])
    print(fs+ls+dif)

if __name__=='__main__':
    main()

Solution (Python):
import sys
import heapq

def main():
    rl=sys.stdin.readline
    n=int(rl().strip())
    a=list(map(int,rl().strip().split()))
    b=[-x for x in a]
    b.reverse()
    fl=a[:n]
    fs=sum(fl)
    ll=b[:n]
    ls=sum(ll)
    fdl=[0]*(n+1)
    ldl=[0]*(n+1)
    heapq.heapify(fl)
    heapq.heapify(ll)
    for i in range(1,n+1):
        fmn=heapq.heappushpop(fl,a[n+i-1])
        lmn=heapq.heappushpop(ll,b[n+i-1])
        fdl[i]=fdl[i-1]+a[n+i-1]-fmn
        ldl[i]=ldl[i-1]+b[n+i-1]-lmn
    ldl.reverse()
    dif=max([x+y for x,y in zip(fdl,ldl)])
    print(fs+ls+dif)

if __name__=='__main__':
    main()

Solution (Python):
from heapq import heapify, heappushpop
n = int(input())
a = list(map(int, input().split()))
a1 = a[:n]
heapify(a1)
a2 = a[n:2*n]
a3 = [-i for i in a[2*n:]]
heapify(a3)
b1 = [sum(a1)]
b2 = [sum(a3)]
for i in range(n):
    b1.append(b1[-1]+a2[i]-heappushpop(a1, a2[i]))
    b2.append(b2[-1]-heappushpop(a3, -a2[n-i-1])-a2[n-i-1])
ans = b1[0]+b2[n]
for i in range(n+1):
    ans = max(ans, b1[i]+b2[n-i])
print(ans)

Solution (Python):
from heapq import heapify, heapreplace
n = int(input())
a = list(map(int, input().split()))
a1 = a[:n]
heapify(a1)
a2 = a[n:2*n]
a3 = [-i for i in a[2*n:]]
heapify(a3)
b1 = [sum(a1)]
b2 = [sum(a3)]
for i in range(n):
    b1.append(a2[i]-heapreplace(a1, a2[i]))
    b2.append(-heapreplace(a3, -a2[n-i-1])-a2[n-i-1])
for i in range(n):
    b1[i+1] += b1[i]
    b2[i+1] += b2[i]
accu = []
mx = b1[0]
for i in b1:
    mx = max(mx, i)
    accu.append(mx)
ans = -10**16
mx = b2[0]
for i in range(n+1):
    mx = max(mx, b2[i])
    ans = max(ans, mx+accu[n-i])
print(ans)

Solution (Python):
import copy
import heapq
N = int(input())
A = list(map(int, input().split()))

h1 = copy.deepcopy(A[:N])
x = sorted(A[N:])
h2 = x[N:]
x = x[:N]

now_w = sum(h1) - sum(x)
ans = now_w
used = []
heapq.heapify(h1)
heapq.heapify(h2)
heapq.heapify(used)

for i in range(N):
  now = A[N+i]
  heapq.heappush(h1, now)
  left = heapq.heappop(h1)
  while True:
    right_cand = heapq.heappop(h2)
    if len(used) > 0:
      x = heapq.heappop(used)
      if x == right_cand:
        continue
      else:
        heapq.heappush(used, x)
    break
      
  if right_cand >= now:
    right = right_cand
  else:
    right = now
    heapq.heappush(h2, right_cand)
    heapq.heappush(used, now)
  now_w = now_w - left + 2*now - right
  
  ans = max(ans, now_w)
  
print(ans)

Solution (Python):
import copy
import heapq
N = int(input())
A = list(map(int, input().split()))

h1 = copy.deepcopy(A[:N])
x = sorted(A[N:])
h2 = x[N:]
x = x[:N]

now_w = sum(h1) - sum(x)
ans = now_w
used = []
heapq.heapify(h1)
heapq.heapify(h2)
heapq.heapify(used)

for i in range(N):
  now = A[N+i]
  heapq.heappush(h1, now)
  left = heapq.heappop(h1)
  while True:
    right_cand = heapq.heappop(h2)
    if len(used) > 0:
      x = heapq.heappop(used)
      if x == right_cand:
        continue
      else:
        heapq.heappush(used, x)
    break
      
  if right_cand >= now:
    right = right_cand
  else:
    right = now
    heapq.heappush(h2, right_cand)
    heapq.heappush(used, now)
  now_w = now_w - left + 2*now - right
  
  ans = max(ans, now_w)
  
print(ans)

Solution (Python):
from heapq import heapify,heappop,heappush
N=int(input())
a=list(map(int,input().split()))
ans=-10**18
a_neg=[-x for x in a]
af=a[:N]
ae=a_neg[2*N:]
f_sum=[sum(af)]
e_sum=[sum(ae)]

heapify(af)
for aa in a[N:2*N]:
  heappush(af,aa)
  t=heappop(af)
  f_sum.append(f_sum[-1]+aa-t)

heapify(ae)
for aa in reversed(a[N:2*N]):
  heappush(ae,-aa)
  t=heappop(ae)
  e_sum.append(e_sum[-1]-aa-t)

for f,e in zip(f_sum,reversed(e_sum)):
  ans=max(ans,f+e)

print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(4100000)
import math
import itertools
INF = 10**20
from heapq import heapify, heappop, heappush


def main():
    n = int(input())
    A = list(map(int, input().split()))

    L = A[:n]
    R = A[2*n:]
    R = list(map(lambda x:x*(-1), R))
    sum_l = [sum(L)]
    sum_r = [sum(R)]
    heapify(L)
    heapify(R)
    for i in range(n):
        elem = A[n+i]
        heappush(L, elem)
        sum_l.append(sum_l[-1] + elem - heappop(L))
    for i in range(n):
        elem = -A[2*n-1-i]
        heappush(R,elem)
        sum_r.append(sum_r[-1] + elem - heappop(R))
    ans = -INF
    sum_r = sum_r[::-1]
    for i in range(len(sum_l)):
        ans = max(ans, sum_l[i]+sum_r[i])
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import heapq
n=int(input())
A=list(map(int,input().split()))
A_l=A[:n]
heapq.heapify(A_l)
A_l_sum=[sum(A_l)]
A_m=A[n:2*n]
for i in range(n):
    p=A_m[i]
    heapq.heappush(A_l,p)
    q=heapq.heappop(A_l)
    A_l_sum.append(A_l_sum[-1]+p-q)
A_r=A[2*n:3*n]
for i in range(n):
    A_r[i]*=-1
for i in range(n):
    A_m[i]*=-1
A_m=A_m[::-1]
heapq.heapify(A_r)
A_r_sum=[sum(A_r)]
for i in range(n):
    p=A_m[i]
    heapq.heappush(A_r,p)
    q=heapq.heappop(A_r)
    A_r_sum.append(A_r_sum[-1]+p-q)
ans=-float("INF")
for i in range(n+1):
    ans=max(ans,A_l_sum[i]+A_r_sum[-i-1])
print(ans)

Solution (Python):
import sys
readline = sys.stdin.readline

N = int(readline())
A = list(map(int,readline().split()))















from collections import defaultdict

sortA = sorted(A[:2 * N])
smallA = sortA[:N]
small_dic = defaultdict(int)
for i in range(len(smallA)):
  small_dic[smallA[i]] += 1
largeA = sortA[N:]
large_dic = defaultdict(int)
for i in range(len(largeA)):
  large_dic[largeA[i]] += 1

leftsum = sum(sortA[N:])

import heapq as hq
leftq = list(map(lambda x:-x,smallA))
hq.heapify(leftq)

rightq = A[2 * N:]
rightsum = sum(rightq)
rightq = list(map(lambda x:-x,rightq))
hq.heapify(rightq)

ans = leftsum - rightsum


for i in range(2 * N - 1, N - 1, -1):
  
  if large_dic[A[i]] > 0: 
    large_dic[A[i]] -= 1
    leftsum -= A[i]
    while True:
      move = -hq.heappop(leftq)
      if small_dic[move] > 0:
        small_dic[move] -= 1
        break
    leftsum += move
    large_dic[move] += 1
    
  else:
    small_dic[A[i]] -= 1
    
  hq.heappush(rightq, -A[i])
  rem = -hq.heappop(rightq)
  rightsum += A[i]
  rightsum -= rem
  
  if ans < leftsum - rightsum:
    ans = leftsum - rightsum
  
    
print(ans)

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7





N = getN()
A = getList()

fore = A[:N]
back = A[2 * N:]
back = [-i for i in back]
for_sum = sum(fore)
back_sum = sum(back)
heapq.heapify(fore)
heapq.heapify(back)

fore_list = []
back_list = []
for i in range(N):
    fore_list.append(for_sum)
    back_list.append(back_sum)
    in_fore = A[N + i]
    heapq.heappush(fore, in_fore)
    out_fore = heapq.heappop(fore)
    for_sum += in_fore - out_fore

    in_back = (-1) * A[-N - i - 1]
    heapq.heappush(back, in_back)
    out_back = heapq.heappop(back)
    back_sum += in_back - out_back

fore_list.append(for_sum)
back_list.append(back_sum)

ans = -float('inf')
for i in range(N + 1):
    opt = fore_list[i] + back_list[N - i]
    ans = max(ans, opt)
print(ans)

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
l=[0]*3*n
r=[-1000000000000000]*3*n
from heapq import heappop,heappush
h=[]
s=0
for i in a[:n]:
  heappush(h,i)
  s+=i
l[n-1]=s
for i in range(n,2*n):
  heappush(h,a[i])
  s+=a[i]
  s-=heappop(h)
  l[i]=s
h=[]
s=0
for i in a[2*n:]:
  heappush(h,-i)
  s+=-i
for i in range(2*n-1,n-2,-1):
  r[i]=s
  heappush(h,-a[i])
  s+=-a[i]
  s-=heappop(h)
print(max(l[i]+r[i]for i in range(3*n)))

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
ans=-10**18
a_minus=[-x for x in a]
af=a[:n]
ae=a_minus[2*n:]
f_sum=[sum(af)]
e_sum=[sum(ae)]
from heapq import heapify,heappop,heappush
heapify(af)
for aa in a[n:2*n]:
  heappush(af,aa)
  t=heappop(af)
  f_sum.append(f_sum[-1]+aa-t)
heapify(ae)
for aa in reversed(a[n:2*n]):
  heappush(ae,-aa)
  t=heappop(ae)
  e_sum.append(e_sum[-1]-aa-t)
for f,e in zip(f_sum,reversed(e_sum)):
  ans=max(ans,f+e)
print(ans)

Solution (Python):
import heapq

N = int(input())
A = list(map(int, input().split()))
l, r = [], []
ll = 0
for i in range(3*N):
    if i < N:
        heapq.heappush(l, (A[i], i))
        ll += A[i]
    else:
        heapq.heappush(r, (A[i], i))
used = set()
rr = 0
for i in range(N):
    a, idx = heapq.heappop(r)
    used.add(idx)
    rr += a
ans = ll-rr
done = set()
for i in range(N,2*N):
    done.add(i)
    if A[i] > l[0][0]:
        ll -= l[0][0]
        heapq.heappop(l)
        heapq.heappush(l, (A[i], i))
        ll += A[i]
    if i in used:
        rr -= A[i]
        a, idx = heapq.heappop(r)
        while idx in done:
            a, idx = heapq.heappop(r)
        used.add(idx)
        rr += a
    
    ans = max(ans, ll-rr)
print(ans)

Solution (Python):
import sys,collections as cl,bisect as bs,heapq as hq
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): 
	return list(map(int,input().split()))
def m(): 
	return map(int,input().split())
def onem(): 
	return int(input())
def s(x): 
	a = []
	if len(x) == 0:
		return []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa != x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x): 
	return " ".join(map(str,x))
def max2(x): 
	return max(map(max,x))
def In(x,a): 
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def pow_k(x, n):
    ans = 1
    while n:
        if n % 2:
            ans *= x
        x *= x
        n >>= 1
    return ans

"""
def nibu(x,n,r):
	ll = 0
	rr = r
	while True:
		mid = (ll+rr)//2

	if rr == mid:
		return ll
	if (ここに評価入れる):
		rr = mid
	else:
		ll = mid+1
"""


n = onem()

a = l()

fl = a[:n]
ba = a[2*n:]



ba = list(map(lambda x:-x,ba))

po = cl.deque(a[n:2*n])

hq.heapify(fl)
fll = fl
hq.heapify(ba)
baa = ba
al = [sum(fll),sum(baa)]
best = [[0,0] for i in range(n+1)]
best[0] = [al[0],0]
best[-1] = [0,al[1]]
for i in range(n):
	aaa = hq.heappop(fll)
	bbb = po[i]
	if bbb >= aaa:
		hq.heappush(fll,bbb)
		best[i+1][0] = al[0] - aaa + bbb
		al[0] += -aaa + bbb
	else:
		hq.heappush(fll,aaa)
		best[i+1][0] = al[0]

for i in range(n-1,-1,-1):
	aaa = hq.heappop(baa)
	bbb = -po[i]
	if aaa <= bbb:
		hq.heappush(baa,bbb)
		best[i][1] = al[1] - aaa + bbb
		al[1] += -aaa + bbb
	else:
		hq.heappush(baa,aaa)
		best[i][1] = al[1]

ans = -Max

for i in range(n+1):
	ans = max(ans,best[i][0]+best[i][1])

print(ans)

Solution (Python):
from heapq import heappop, heappush, heapify


def main():
    n = int(input())
    A = list(map(int, input().split()))

    left_sums = []
    left = A[:n]
    left_sum = sum(left)
    left_sums.append(left_sum)
    heapify(left)

    for a in A[n:2*n]:
        left_sum += a
        heappush(left, a)
        left_sum -= heappop(left)
        left_sums.append(left_sum)

    right_sums = []
    right = []
    for a in A[2*n:]:
        right.append(-a)
    right_sum = sum(right)
    right_sums.append(-right_sum)
    heapify(right)

    for a in A[2*n-1:n-1:-1]:
        right_sum += -a
        heappush(right, -a)
        right_sum -= heappop(right)
        right_sums.append(-right_sum)

    candidates = []
    for sum1, sum2 in zip(left_sums, right_sums[::-1]):
        candidates.append(sum1 - sum2)

    print(max(candidates))


if __name__ == "__main__":
    main()

Solution (Python):
N = int(input())

A = list(map(int,input().split()))
import heapq
L = A[:N]
heapq.heapify(L)
sum_L = sum(A[:N])
L_list = []
L_list.append(sum_L)
for i in range(N):
    sum_L += A[N+i]
    heapq.heappush(L,A[N+i])
    sum_L -= heapq.heappop(L)
    L_list.append(sum_L)

A = list(map(lambda x:-x, A[::-1]))
R = A[:N]
heapq.heapify(R)
sum_R = sum(A[:N])
R_list = []
R_list.append(sum_R)


for i in range(N):
    sum_R += A[N+i]
    heapq.heappush(R,A[N+i])
    sum_R -= heapq.heappop(R)
    R_list.append(sum_R)
maxi = -10000000000000000000000000000
R_list = R_list[::-1]
for i in range(N+1):
    maxi = max(maxi,L_list[i] + R_list[i])

print(maxi)

Solution (Python):
N = int(input())

A = list(map(int,input().split()))
import heapq
L = A[:N]
heapq.heapify(L)
sum_L = sum(A[:N])
L_list = []
L_list.append(sum_L)
for i in range(N):
    sum_L += A[N+i]
    heapq.heappush(L,A[N+i])
    sum_L -= heapq.heappop(L)
    L_list.append(sum_L)

A = list(map(lambda x:-x, A[::-1]))
R = A[:N]
heapq.heapify(R)
sum_R = sum(A[:N])
R_list = []
R_list.append(sum_R)


for i in range(N):
    sum_R += A[N+i]
    heapq.heappush(R,A[N+i])
    sum_R -= heapq.heappop(R)
    R_list.append(sum_R)
maxi = -10000000000000000000000000000
R_list = R_list[::-1]
for i in range(N+1):
    maxi = max(maxi,L_list[i] + R_list[i])

print(maxi)