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.



Sample input:
2
3 1 4 1 5 9


Sample output:
1

Submission status: Runtime Error

Solution code:
import sys
fin = sys.stdin.readline
from heapq import heappop, heappush, heapify


class BSTNode(object):
    """A node in the vanilla BST tree."""
    
    def __init__(self, parent, k):
        """Creates a node.
        
        Args:
            parent: The node's parent.
            k: key of the node.
        """
        self.key = k
        self.parent = parent
        self.left = None
        self.right = None
  
    def _str(self):
        """Internal method for ASCII art."""
        label = str(self.key)
        if self.left is None:
            left_lines, left_pos, left_width = [], 0, 0
        else:
            left_lines, left_pos, left_width = self.left._str()
        if self.right is None:
            right_lines, right_pos, right_width = [], 0, 0
        else:
            right_lines, right_pos, right_width = self.right._str()
        middle = max(right_pos + left_width - left_pos + 1, len(label), 2)
        pos = left_pos + middle // 2
        width = left_pos + middle + right_width - right_pos
        while len(left_lines) < len(right_lines):
            left_lines.append(' ' * left_width)
        while len(right_lines) < len(left_lines):
            right_lines.append(' ' * right_width)
        if (middle - len(label)) % 2 == 1 and self.parent is not None and \
           self is self.parent.left and len(label) < middle:
            label += '.'
        label = label.center(middle, '.')
        if label[0] == '.': label = ' ' + label[1:]
        if label[-1] == '.': label = label[:-1] + ' '
        lines = [' ' * left_pos + label + ' ' * (right_width - right_pos),
                 ' ' * left_pos + '/' + ' ' * (middle-2) +
                 '\\' + ' ' * (right_width - right_pos)] + \
          [left_line + ' ' * (width - left_width - right_width) + right_line
           for left_line, right_line in zip(left_lines, right_lines)]
        return lines, pos, width
    def __str__(self):
        return '\n'.join(self._str()[0])

    def find(self, k):
        """Finds and returns the node with key k from the subtree rooted at this 
        node.
        
        Args:
            k: The key of the node we want to find.
        
        Returns:
            The node with key k.
        """
        if k == self.key:
            return self
        elif k < self.key:
            if self.left is None:
                return None
            else:
                return self.left.find(k)
        else:
            if self.right is None:  
                return None
            else:
                return self.right.find(k)
    
    def find_min(self):
        """Finds the node with the minimum key in the subtree rooted at this 
        node.
        
        Returns:
            The node with the minimum key.
        """
        current = self
        while current.left is not None:
            current = current.left
        return current
       
    def next_larger(self):
        """Returns the node with the next larger key (the successor) in the BST.
        """
        if self.right is not None:
            return self.right.find_min()
        current = self
        while current.parent is not None and current is current.parent.right:
            current = current.parent
        return current.parent

    def insert(self, node):
        """Inserts a node into the subtree rooted at this node.
        
        Args:
            node: The node to be inserted.
        """
        if node is None:
            return
        if node.key < self.key:
            if self.left is None:
                node.parent = self
                self.left = node
            else:
                self.left.insert(node)
        else:
            if self.right is None:
                node.parent = self
                self.right = node
            else:
                self.right.insert(node)
  
    def delete(self):
        """Deletes and returns this node from the BST."""
        if self.left is None or self.right is None:
            if self is self.parent.left:
                self.parent.left = self.left or self.right
                if self.parent.left is not None:
                    self.parent.left.parent = self.parent
            else:
                self.parent.right = self.left or self.right
                if self.parent.right is not None:
                    self.parent.right.parent = self.parent
            return self
        else:
            s = self.next_larger()
            self.key, s.key = s.key, self.key
            return s.delete()
    
    def check_ri(self):
        """Checks the BST representation invariant around this node.
    
        Raises an exception if the RI is violated.
        """
        if self.left is not None:
            if self.left.key > self.key:
                raise RuntimeError("BST RI violated by a left node key")
            if self.left.parent is not self:
                raise RuntimeError("BST RI violated by a left node parent "
                                   "pointer")
            self.left.check_ri()
        if self.right is not None:
            if self.right.key < self.key:
                raise RuntimeError("BST RI violated by a right node key")
            if self.right.parent is not self:
                raise RuntimeError("BST RI violated by a right node parent "
                                   "pointer")
            self.right.check_ri()

class MinBSTNode(BSTNode):
    """A BSTNode which is augmented to keep track of the node with the 
    minimum key in the subtree rooted at this node.
    """
    def __init__(self, parent, key):
        """Creates a node.
        
        Args:
            parent: The node's parent.
            k: key of the node.
        """
        super(MinBSTNode, self).__init__(parent, key)
        self.min = self
  
    def find_min(self):
        """Finds the node with the minimum key in the subtree rooted at this 
        node.
        
        Returns:
            The node with the minimum key.
        """
        return self.min

    def insert(self, node):
        """Inserts a node into the subtree rooted at this node.
        
        Args:
            node: The node to be inserted.
        """
        if node is None:
            return
        if node.key < self.key:
            # Updates the min of this node if the inserted node has a smaller
            # key.
            if node.key < self.min.key:
                self.min = node
            if self.left is None:
                node.parent = self
                self.left = node
            else:
                self.left.insert(node)
        else:
            if self.right is None:
                node.parent = self
                self.right = node
            else:
                self.right.insert(node)
  
    def delete(self):
        """Deletes this node itself.
        
        Returns:
            This node.
        """
        if self.left is None or self.right is None:
            if self is self.parent.left:
                self.parent.left = self.left or self.right
                if self.parent.left is not None:
                    self.parent.left.parent = self.parent
                    self.parent.min = self.parent.left.min
                else: 
                    self.parent.min = self.parent
                # Propagates the changes upwards.
                c  = self.parent
                while c.parent is not None and c is c.parent.left:
                    c.parent.min = c.min
                    c = c.parent
            else:
                self.parent.right = self.left or self.right
                if self.parent.right is not None:
                    self.parent.right.parent = self.parent
            return self
        else:
            s = self.next_larger()
            self.key, s.key = s.key, self.key
            return s.delete()

class BST(object):
    """A binary search tree."""
    def __init__(self, klass = BSTNode):
        """Creates an empty BST.
        
        Args:
            klass (optional): The class of the node in the BST. Default to 
                BSTNode.
        """
        self.root = None
        self.klass = klass
        
    def __str__(self):
        if self.root is None: return '<empty tree>'
        return str(self.root)

    def find(self, k):
        """Finds and returns the node with key k from the subtree rooted at this 
        node.
        
        Args:
            k: The key of the node we want to find.
        
        Returns:
            The node with key k or None if the tree is empty.
        """
        return self.root and self.root.find(k)
                
    def find_min(self):
        """Returns the minimum node of this BST."""
        
        return self.root and self.root.find_min()
    
    def insert(self, k):
        """Inserts a node with key k into the subtree rooted at this node.
        
        Args:
            k: The key of the node to be inserted.
            
        Returns:
            The node inserted.
        """
        node = self.klass(None, k)
        if self.root is None:
            # The root's parent is None.
            self.root = node
        else:
            self.root.insert(node)
        return node
            
    def delete(self, k):
        """Deletes and returns a node with key k if it exists from the BST.
        
        Args:
            k: The key of the node that we want to delete.
            
        Returns:
            The deleted node with key k.
        """
        node = self.find(k)
        if node is None:
            return None
        if node is self.root:
            pseudoroot = self.klass(None, 0)
            pseudoroot.left = self.root
            self.root.parent = pseudoroot
            deleted = self.root.delete()
            self.root = pseudoroot.left
            if self.root is not None:
                self.root.parent = None
            return deleted
        else:
            return node.delete()   
        
    def next_larger(self, k):
        """Returns the node that contains the next larger (the successor) key in
        the BST in relation to the node with key k.
        
        Args:
            k: The key of the node of which the successor is to be found.
            
        Returns:
            The successor node.
        """
        node = self.find(k)
        return node and node.next_larger()
    
    def check_ri(self):
        """Checks the BST representation invariant.
        
        Raises:
            An exception if the RI is violated.
        """
        if self.root is not None:
            if self.root.parent is not None:
                raise RuntimeError("BST RI violated by the root node's parent " 
                                   "pointer.")
            self.root.check_ri()
    

class MinBST(BST):
    """An augmented BST that keeps track of the node with the minimum key."""
    def __init__(self):
        super(MinBST, self).__init__(MinBSTNode)


def height(node):
    if node is None:
        return -1
    else:
        return node.height


def update_height(node):
    node.height = max(height(node.left), height(node.right)) + 1


class AVL(BST):
    """
AVL binary search tree implementation.
Supports insert, delete, find, find_min, next_larger each in O(lg n) time.
"""
    def left_rotate(self, x):
        y = x.right
        y.parent = x.parent
        if y.parent is None:
            self.root = y
        else:
            if y.parent.left is x:
                y.parent.left = y
            elif y.parent.right is x:
                y.parent.right = y
        x.right = y.left
        if x.right is not None:
            x.right.parent = x
        y.left = x
        x.parent = y
        update_height(x)
        update_height(y)

    def right_rotate(self, x):
        y = x.left
        y.parent = x.parent
        if y.parent is None:
            self.root = y
        else:
            if y.parent.left is x:
                y.parent.left = y
            elif y.parent.right is x:
                y.parent.right = y
        x.left = y.right
        if x.left is not None:
            x.left.parent = x
        y.right = x
        x.parent = y
        update_height(x)
        update_height(y)

    def rebalance(self, node):
        while node is not None:
            update_height(node)
            if height(node.left) >= 2 + height(node.right):
                if height(node.left.left) >= height(node.left.right):
                    self.right_rotate(node)
                else:
                    self.left_rotate(node.left)
                    self.right_rotate(node)
            elif height(node.right) >= 2 + height(node.left):
                if height(node.right.right) >= height(node.right.left):
                    self.left_rotate(node)
                else:
                    self.right_rotate(node.right)
                    self.left_rotate(node)
            node = node.parent

    ## find(k), find_min(), and next_larger(k) inherited from bst.BST

    def insert(self, k):
        """Inserts a node with key k into the subtree rooted at this node.
        This AVL version guarantees the balance property: h = O(lg n).
        
        Args:
            k: The key of the node to be inserted.
        """
        node = super(AVL, self).insert(k)
        self.rebalance(node)

    def delete(self, k):
        """Deletes and returns a node with key k if it exists from the BST.
        This AVL version guarantees the balance property: h = O(lg n).
        
        Args:
            k: The key of the node that we want to delete.
            
        Returns:
            The deleted node with key k.
        """
        node = super(AVL, self).delete(k)
        ## node.parent is actually the old parent of the node,
        ## which is the first potentially out-of-balance node.
        self.rebalance(node.parent)


N = int(fin())
a_list = [int(elem) for elem in fin().split()]
left, right = a_list[:N], a_list[N:]

thrown_away = [False] * (2 * N)
discarded_items = AVL(MinBSTNode)

# initialize
right_sum = sum(right)
for i, item in enumerate(right):
    if i < N:
        discarded_items.insert((item, i))
        thrown_away[i] = True
        right_sum -= item
    else:
        min_key = discarded_items.find_min().key
        if item > min_key[0]:
            discarded_items.delete(min_key)
            old_item, old_idx = min_key
            thrown_away[old_idx] = False
            discarded_items.insert((item, i))
            thrown_away[i] = True
            right_sum += old_item - item


# move partitions and calculate a global maximum
left_sum = sum(left)
heapify(left)
max_score = left_sum - right_sum
for i, item in enumerate(right[:N]):
    if not thrown_away[i]:
        # update right
        min_key = discarded_items.find_min().key
        updated_item, updated_idx = min_key
        discarded_items.delete(min_key)
        right_sum += updated_item - item
        thrown_away[updated_idx] = False
    else:
        # want to update discarded_items
        discarded_items.delete((item, i))
    # update left
    if item > left[0]:
        old_item = heappop(left)
        heappush(left, item)
        left_sum += item - old_item
    max_score = max(max_score, left_sum - right_sum)

print(max_score)

Submission status: Runtime Error

Solution code:

# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from pprint import pprint
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(10000)


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def Prim(g):
    V = list(g.keys())
    for v in g.values():
        V.extend(list(v.keys()))
    V = list(set(V))

    used = set([])
    q = []
    heapq.heappush(q, (0, V[0]))

    ret = 0
    while q:
        c, v = heapq.heappop(q)

        if v in used:
            continue
        used.add(v)
        ret += c
        for u in g[v]:
            heapq.heappush(q, (g[v][u], u))
    return ret


@mt
def slv(N, A):
    q = []
    lc = [0]*(N+1)
    for i in range(N):
        heapq.heappush(q, A[i])
        lc[0] += A[i]
    for i in range(N, 2*N):

        a = heapq.heappushpop(q, A[i])
        lc[i-N+1] = lc[i-N] + A[i] - a

    q = []
    rc = [0] * (N+1)
    for i in range(3*N-1, 2*N-1, -1):
        heapq.heappush(q, -A[i])
        rc[N] += A[i]
    for i in range(2*N-1, N-1, -1):
        a = -heapq.heappushpop(q, -A[i])
        rc[i-N] = rc[i-N+1] + A[i] - a

    return max(map(sub, zip(lc, rc)))


def main():
    N = read_int()
    A = read_int_n()

    print(slv(N, A))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import bisect
N = int(input())
A = list(map(int, input().split()))

L = sorted(A[:2*N])
sumL = sum(L[N:])
R = sorted(A[N:])
sumR = sum(R[:N])

AL = [sumL]
p = N
for a in reversed(A[N:2*N]):  # sumLはだんだん減る
    ind = bisect.bisect_left(L, a)
    if ind >= p:
        sumL -= L[ind]
        p -= 1
        while L[p] == False:
            p -= 1
        sumL += L[p]
    AL.append(sumL)
    L[ind] = False
AR = [sumR]
p = N-1
for a in A[N:2*N]:  # sumRはだんだん増える
    ind = bisect.bisect_left(R, a)
    if ind <= p:
        sumR -= R[ind]
        p += 1
        while R[p] == False:
            p += 1
        sumR += R[p]
    AR.append(sumR)
    R[ind] = False
AL.reverse()
C = [AL[i] - AR[i] for i in range(N+1)]
print(max(C))

Submission status: Runtime Error

Solution code:
import heapq

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

red, blue = a[:n], [-1*i for i in a[2*n:]]
sr, sb = sum(red), sum(blue)

results = [0] * (n + 1)
results[0] = sr
results[-1] = sb

heapq.heapify(red)
heapq.heapify(blue)

for k in range(n, 2*n):
    v = a[k]
    p = heapq.heappushpop(red, v)
    sr += v - p
    results[i-n+1] += sr

for k in range(2*n-1, n-1, -1):
    v = -1 * a[k]
    p = heapq.heappushpop(blue, v)
    sb += v - p
    results[i-n] += sb

print(max(results))

Submission status: Runtime Error

Solution code:
import queue
N=int(input())
a=list(map(int,input().split()))
sl=[0]*(N+1)
ft=sum(a[:N])
st=sum(a[2*N:])
fa=queue.PriorityQueue(N+1)
sa=queue.PriorityQueue(N+1)
sl[0]=ft
sl[N]=-st
for i in range(N):
    fa.put(a[i]);sa.put((-1*a[i+2*N],a[i+2*N]))
for k in range(N,2*N):
    fa.put(a[k],timeout=2)
    ft+=a[k]
    ft-=(fa.get(timeout=2))
    sl[k-N+1]+=ft
for k in range(N,2*N):
    rk=3*N-k-1
    sa.put((-1*a[rk],a[rk]),timeout=2)
    st+=a[rk]
    st-=(sa.get(timeout=2)[1])
    sl[rk-N]-=st
print(max(max(sl),T))

Submission status: Runtime Error

Solution code:
N = int(input())
array = [int(n) for n in input().split()]
import copy
import heapq

lst = [None for i in range(N + 1)]
left_lst = copy.deepcopy(lst)
right_lst = copy.deepcopy(lst)
right_array = heapq.heapify(array[:N])
left_array = heapq.heapify([-n for n in array[-N:]])
l_sum = sum(left_array)
r_sum = sum(right_array)
left_lst[0] = l_sum
right_lst[0] = r_sum

for k in range(N, 2 * N):
    new_a, new_b = array[k], array[-k - 1]*-1
    heapq.heappush(left_array,new_a)
    heapq.heappush(right_array,new_b)
    old_a = heapq.heappop(left_array)
    l_sum += (new_a - old_a)
    left_lst[k - N + 1] = l_sum
    right_array.append(new_b)
    old_b = heapq.heappop(right_array)
    r_sum += (new_b - old_b)
    right_lst[k - N + 1] = r_sum
lst = [a + b for a, b in zip(left_lst, list(reversed(right_lst)))]
print(max(lst))

Submission status: Runtime Error

Solution code:
N = int(input())
array=[int(n) for n in input().split()]
    lst=[]
    left_array=array[:N]
    right_array=array[-N:]
    for i in range(N+1):
        for j in range(i):
            new_a=array[N+j+1]
            old_a=min(left_array)
            new_b=array[-N-j-1]
            old_b=min(right_array)
            left_array.append(new_a)
            left_array.remove(old_a)
            right_array.append(new_b)
            right_array.remove(old_b)
    lst.append(sum(left_array)-sum(right_array))
    print(max(lst))

Submission status: Runtime Error

Solution code:
N = int(input())
array=[int(n) for n in input().split()]
lst=[]
for i in range(N+1):
    left_array=array[:N+i]
    print(left_array)
    l = sorted(left_array)[-N:]
    print('l:',l)
    right_array=array[N+i:]
    print(right_array)
    r = sorted(right_array)[:N]
    print('r:',r)
    ans = sum(l)-sum(r)
    print(ans)
    lst.append(ans)
print(max(lst))

Submission status: Runtime Error

Solution code:
N = int(input())
array=[int(n) for n in input().split()]
lst=[]
for i in range(N+1):
    left_array=array[:N+i]
    l = sorted(left_array)[-N:]
    right_array=array[N+i:]
    r = sorted(right_array)[:N]
    ans = sum(l)-sum(r)
    lst.extend(ans)
print(lst)

Submission status: Runtime Error

Solution code:
N = int(input())
array=[int(n) for n in input().split()]

lst=0
for i in range(N+1):
    left_array=array[:N+i]
    print(left_array)
    l = sorted(left_array)[-N:]
    print('l:',l)
    right_array=array[N+i:]
    print(right_array)
    r = sorted(right_array)[:N]
    print('r:',r)
    ans = sum(l)-sum(r)
    print(ans)
    if ans > lst:
        lst= ans
print(lst)

Submission status: Runtime Error

Solution code:
N = int(input())
array=[int(n) for n in input().split()]

lst=0
for i in range(N+1):
    left_array=array[:N+i]
    print(left_array)
    l = sorted(left_array)[-N:]
    print('l:',l)
    right_array=array[-int(N)+i-3:]
    print(right_array)
    r = sorted(right_array)[:N]
    print('r:',r)
    ans = sum(l)-sum(r)
    print(ans)
    if ans > lst:
        lst= ans
print(lst)

Submission status: Runtime Error

Solution code:
N = input()
array= input().split()
left_array=array[:array/3+1]
mid_array= array[array/3+1:-array/3]
right_array= array[-array/3]
lst=0
for i in N:
    left_array=array[:array/3+i+1]
    l = left_array.sort()[i+1:]
    right_array=array[-array/3+i+1:]
    r = right_array.sort(reverse=True)[N-i-1:]
    ans = sum(abs(l-r))
    if ans > lst:
        lst= ans
print(lst)

Submission status: Runtime Error

Solution code:
N = input()
array= input().split()
left_array=array[:array/3+1]
mid_array= array[array/3+1:-array/3]
right_array= array[-array/3]
lst=[]
for i in N:
    left_array=array[:array/3+i+1]
    l = left_array.sort()[i+1:]
    right_array=array[-array/3+i+1:]
    r = right_array.sort(reverse=True)[N-i-1:]
    ans = sum(abs(l-r))
    if ans > lst:
        lst= ans
print(lst)

Submission status: Runtime Error

Solution code:
N = int(input())
a = list(map(int,input().split()))

S1 , S2 = {}, {}
for i in range(N):
    S1[a[i]] = S1.get(a[i], 0) + 1

for i in range(2 * N, 3* N):
    S2[a[i]] = S2.get(a[i], 0) + 1

i = N
j = 2 * N - 1

minS1 = min(S1)
maxS2 = max(S2)

while i <= j:
    delS1 = a[i] - minS1
    delS2 = maxS2 - a[j]

    if delS1 >= 0 and delS1 >= delS2:
        #print("chang S1")
        val = S1.pop(minS1)
        if val >= 2:
            S1[minS1] = val - 1
        S1[a[i]] = S1.get(a[i], 0) + 1
        minS1 = min(S1)
        i += 1

    elif delS2 >= 0:
        val = S2.pop(maxS2)
        if val >= 2:
            S2[minS2] = val - 1
        S2[a[j]] = S2.get(a[j], 0) + 1
        maxS2 = max(S2)
        j -= 1

    else:
        i += 1

sumS1, sumS2 = 0, 0
for i in S1.items():
    sumS1 += i[0] * i[1]
for j in S2.items():
    sumS2 += j[0] * j[1]

print(sumS1 - sumS2)

Submission status: Runtime Error

Solution code:
def f(a):
	s=0;q=a[:n];s=sum(q);heapify(q);yield s
	for e in a[n:2*n]:s+=e-heappushpop(q,e);yield s
from heapq import*;r=reversed;n,*a=map(int,open(0).read().split());print(max(map(sum,zip(f(a),r(f([-e for e in r(a)]))))))

Submission status: Runtime Error

Solution code:
def f(a):
	s=0;q=[]
	for i in range(n):s+=a[i];heappush(q,a[i])
	r=[s]
	for i in range(n,2*n):s+=a[i];s-=heappushpop(q,a[i]);r+=[s]
	return r
import sys;from heapq import*;n,*a=list(map(int,sys.stdin.read().split()));print(max(x+y for x,y in zip(f(a),f(list(reversed(-e for e in a))))))

Submission status: Runtime Error

Solution code:
def f(a):
	s=0;q=[]
	for i in range(n):s+=a[i];heappush(q,a[i])
	r=[s]
	for i in range(n,2*n):s+=a[i];s-=heappushpop(q,a[i]);r+=[s]
	return r
import sys;from heapq import*;n,*a=list(map(int,sys.stdin.read().split()));print(max(x+y for x,y in zip(f(a),f(reversed(-e for e in a)))))

Submission status: Runtime Error

Solution code:
import heapq

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

max_score = float('-inf')
for i in range(N, 2 * N + 1):
    rm_count_1 = i - N
    rm_count_2 = N - rm_count_1
    a_list_1 = []
    a_list_2 = []
    for k in a[0:i]:
        if len(a_list_1) >= N:
            heappushpop(a_list_1, k)
        else:
            heappush(a_list_1, k)
    for k in a[i:3*N]:
        if len(a_list_2) >= N:
            heappushpop(a_list_2, -k)
        else:
            heappush(a_list_2, -k)
    sum_1 = sum(a_list_1)
    sum_2 = sum(a_list_2)
    score = sum_1 + sum_2
    if score > max_score:
        max_score = score

print(max_score)

Submission status: Runtime Error

Solution code:
from collections import heapq

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

max_score = float('-inf')
for i in range(N, 2 * N + 1):
    rm_count_1 = i - N
    rm_count_2 = N - rm_count_1
    a_list_1 = []
    a_list_2 = []
    for k in a[0:i]:
        if len(a_list_1) >= N:
            heappushpop(a_list_1, k)
        else:
            heappush(a_list_1, k)
    for k in a[i:3*N]:
        if len(a_list_2) >= N:
            heappushpop(a_list_2, -k)
        else:
            heappush(a_list_2, -k)
    sum_1 = sum(a_list_1)
    sum_2 = sum(a_list_2)
    score = sum_1 + sum_2
    if score > max_score:
        max_score = score

print(max_score)

Submission status: Runtime Error

Solution code:
n = int(input())
a = list(map(int,input().split()))
r = []
b = a[:n]
bs = sum(b)
c = sorted(a[n:])
cs = sum(c[:n])
print(b,c,bs,cs,bs-cs)
r.append(bs-cs)
for k in range(n,2*n):
  b.append(a[k])
  bm = min(b)
  b.remove(bm)
  bs = bs + a[k] - bm
  if n <= 1000:
    ci = c.index(a[k])
    if ci < n:
      cs = cs - a[k] + c[n]
    c.pop(ci)
  print(b,c,bs,cs,bs-cs)
  r.append(bs-cs)
print(max(r))

Submission status: Runtime Error

Solution code:
N = int(input())
l_ = input().split()

a = [int(l_[i]) for i in range(N)]
b = [int(l_[i]) for i in range(N, 2*N)]
c = [int(l_[i]) for i in range(N*2, N*3)]

while len(b) > 0:
    front = b[0] - min(a)
    behind = b[-1] - max(c)
    if abs(front) > abs(behind):
        a.remove(min(a))
        a.append(b[0])
        b.remove(b[0])
    elif abs(front) < abs(behind):
        c.remove(max(c))
        c.append(b[-1])
        b.remove(b[-1])
    else:
        x = 1
        y = 1
        while front == behind:
            front = b[x] - min(a)
            behind = b[-y-1] - max(c)
            x += 1
            y += 1
        if abs(front) > abs(behind):
            for i in range(x):
                a.remove(min(a))
                a.append(b[0])
                b.remove(b[0])
        elif abs(front) < abs(behind):
            for i in range(x):
                c.remove(max(c))
                c.append(b[-1])
                b.remove(b[-1])

print( sum(a) - sum(c) )

Submission status: Runtime Error

Solution code:
N = int(input())
l_ = input().split()

a = [l_[i] for i in range(N)]
b = [l_[i] for i in range(N, 2*N)]
c = [l_[i] for i in range(N*2, N*3)]

while len(b) > 0:
    front = b[0] - min(a)
    behind = b[-1] - max(c)
    if abs(front) > abs(behind):
        a.remove(min(a))
        a.append(b[0])
        b.remove(b[0])
    elif abs(front) < abs(behind):
        c.remove(max(c))
        c.append(b[-1])
        b.remove(b[-1])
    else:
        x = 1
        y = 1
        while front == behind:
            front = b[x] - min(a)
            behind = b[-y-1] - max(c)
            x += 1
            y += 1
        if abs(front) > abs(behind):
            for i in range(x):
                a.remove(min(a))
                a.append(b[0])
                b.remove(b[0])
        elif abs(front) < abs(behind):
            for i in range(x):
                c.remove(max(c))
                c.append(b[-1])
                b.remove(b[-1])

print( sum(a) - sum(c) )

Submission status: Runtime Error

Solution code:
N = int(input())
l_ = input().split()

a = [l_[i] for i in range(N)]
b = [l_[i] for i in range(N, 2*N)]
c = [l_[i] for i in range(N*2, N*3)]

while len(b) > 0:
    front = b[0] - min(a)
    behind = b[-1] - max(c)
    if abs(front) > abs(behind):
        a.remove(min(a))
        a.append(b[0])
        b.remove(b[0])
    elif abs(front) < abs(behind):
        c.remove(max(c))
        c.append(b[-1])
        b.remove(b[-1])
    else:
        x = 1
        y = 1
        while front == behind:
            front = b[x] - min(a)
            behind = b[-y-1] - max(c)
            x += 1
            y -= 1
        if abs(front) > abs(behind):
            for i in range(x):
                a.remove(min(a))
                a.append(b[0])
                b.remove(b[0])
        elif abs(front) < abs(behind):
            for i in range(x):
                c.remove(max(c))
                c.append(b[-1])
                b.remove(b[-1])

print( sum(a) - sum(c) )

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import numpy as np

N = int(raw_input())
a = map(int, raw_input().split())

flag = 0
while N > 1:
    l = len(a)
    if flag == 0:
      min = np.argmin(a[:(l//2)])
      a.pop(min)
      N -= 1
      flag = 1

    elif flag == 1:
      max = np.argmax(a[(l//2):]) + l//2
      a.pop(max)
      N -= 1
      flag = 0


min = np.min(a[:(l//2)])
amin = np.argmin(a[:(l//2)])
max = np.max(a[(l//2):])
amax = np.argmax(a[(l//2):]) + l//2
mid = a[(l//2)+1]

if mid - min > - (mid - max):
  a.pop(amin)
else:
  a.pop(amax)

l = len(a)
res = sum(a[:(l//2)]) - sum(a[(l//2):])
print str(res)