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 in C# (Mono 4.6.2.0) (judge verdict: Accepted)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace AtCorder
{
	public class Program
	{
		static void Main(string[] args)
		{
			var cin = new Scanner2();
			int n = cin.Int();
			int m = n * 3;
			var a = cin.ArrayLong(m);

			long leftSum = 0;
			var leftQ = new PriorityQueue<long>(n, true);
			for (int i = 0; i < n; i++) {
				leftSum += a[i];
				leftQ.Enqueue(a[i]);
			}

			var right = a.Where((x, i) => i >= n).ToArray();
			Array.Sort(right);

			var rightRem = new OrderedSet<long>(true);
			long rightSum = 0;
			var rightSet = new OrderedSet<long>((x, y) => y.CompareTo(x), true);
			for (int i = 0; i < n * 2; i++) {
				if (i < n) {
					rightSum += right[i];
					rightSet.Add(right[i]);
				} else {
					rightRem.Add(right[i]);
				}
			}

			long ans = leftSum - rightSum;
			for (int i = 0; i < n; i++) {
				long target = a[i + n];
				if (rightRem.Contains(target)) {
					rightRem.Remove(target);
				} else {
					long next = rightRem[0];
					rightRem.RemoveAt(0);
					rightSet.Remove(target);
					rightSet.Add(next);
					rightSum -= target;
					rightSum += next;
				}

				if (leftQ.Top < target) {
					long rem = leftQ.Dequeue();
					leftQ.Enqueue(target);
					leftSum -= rem;
					leftSum += target;
				} 

				ans = Math.Max(
					ans,
					leftSum - rightSum);
			}

			Console.WriteLine(ans);
		}
	}

	public class OrderedSet<T> : IEnumerable<T>, IReadOnlyCollection<T>
		where T : IComparable
	{
		private readonly bool isMulti_;
		private readonly RandomizedBinarySearchTree<T> bst_
			= new RandomizedBinarySearchTree<T>();
		private RandomizedBinarySearchTree<T>.Node root_;

		public T this[int index] { get { return ElementAt(index); } }

		public OrderedSet(bool isMulti = false, T inf = default(T))
			: this(Comparer<T>.Default, isMulti, inf) { }
		public OrderedSet(Comparison<T> comaprison, bool isMulti = false, T inf = default(T))
			: this(Comparer<T>.Create(comaprison), isMulti, inf) { }
		public OrderedSet(IComparer<T> comparer, bool isMulti = false, T inf = default(T))
		{
			isMulti_ = isMulti;
			bst_ = new RandomizedBinarySearchTree<T>(comparer, inf);
		}

		public int Count { get { return bst_.Count(root_); } }
		public int IndexOf(T v) => bst_.UpperBound(root_, v) - bst_.LowerBound(root_, v);
		public bool Contains(T value) => bst_.Contains(root_, value);

		public void Add(T value)
		{
			if (root_ == null) {
				root_ = new RandomizedBinarySearchTree<T>.Node(value);
			} else {
				if (bst_.Find(root_, value) != null && isMulti_ == false) {
					return;
				}

				root_ = bst_.Insert(root_, value);
			}
		}

		public void Remove(T value)
		{
			root_ = bst_.Remove(root_, value);
		}

		public void RemoveAt(int index)
		{
			root_ = bst_.RemoveAt(root_, index);
		}

		public void Clear()
		{
			root_ = null;
		}

		public T ElementAt(int index)
		{
			var node = bst_.FindByIndex(root_, index);
			if (node == null) {
				throw new IndexOutOfRangeException();
			}

			return node.Value;
		}

		public int LowerBound(T v) => bst_.LowerBound(root_, v);
		public int UpperBound(T v) => bst_.UpperBound(root_, v);
		public T LowerBoundValue(T v) => bst_.LowerBoundValue(root_, v);
		public T UpperBoundValue(T v) => bst_.UpperBoundValue(root_, v);

		public Tuple<int, int> EqualRange(T v)
		{
			if (Contains(v) == false) {
				return new Tuple<int, int>(-1, -1);
			}

			return new Tuple<int, int>(
				bst_.LowerBound(root_, v),
				bst_.UpperBound(root_, v) - 1);
		}

		public List<T> ToList() => new List<T>(bst_.Enumerate(root_));

		public IEnumerator<T> GetEnumerator()
		{
			foreach (var v in bst_.Enumerate(root_)) {
				yield return v;
			};
		}
		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
			=> GetEnumerator();
	}

	public class RandomizedBinarySearchTree<T>
		where T : IComparable
	{
		private static readonly Random random_ = new Random();

		private readonly IComparer<T> comparer_;
		private readonly T inf_;

		public RandomizedBinarySearchTree(T inf = default(T))
			: this(Comparer<T>.Default, inf) { }
		public RandomizedBinarySearchTree(Comparison<T> comaprison, T inf = default(T))
			: this(Comparer<T>.Create(comaprison), inf) { }
		public RandomizedBinarySearchTree(IComparer<T> comparer, T inf = default(T))
		{
			comparer_ = comparer;
			inf_ = inf;
		}

		public int Count(Node node) => node == null ? 0 : node.SubTreeSize;
		public bool Contains(Node node, T value) => Find(node, value) != null;

		public Node Insert(Node node, T value)
		{
			var index = LowerBound(node, value);
			return InsertAt(node, index, value);
		}

		private Node InsertAt(Node node, int k, T value)
		{
			var s = Split(node, k);
			return Merge(Merge(s.Left, new Node(value)), s.Right);
		}

		public Node Remove(Node node, T value)
		{
			if (Find(node, value) == null) {
				return node;
			}

			return RemoveAt(node, LowerBound(node, value));
		}

		public Node RemoveAt(Node node, int k)
		{
			var s1 = Split(node, k);
			var s2 = Split(s1.Right, 1);
			return Merge(s1.Left, s2.Right);
		}

		public Node Find(Node node, T target)
		{
			while (node != null) {
				var cmp = comparer_.Compare(node.Value, target);
				if (cmp > 0) {
					node = node.LeftChild;
				} else if (cmp < 0) {
					node = node.RightChild;
				} else {
					break;
				}
			}
			return node;
		}

		public Node FindByIndex(Node node, int index)
		{
			if (node == null) {
				return null;
			}

			var currentIndex = Count(node) - Count(node.RightChild) - 1;
			while (node != null) {
				if (currentIndex == index) {
					return node;
				}

				if (currentIndex > index) {
					node = node.LeftChild;
					currentIndex -= (Count(node == null ? null : node.RightChild) + 1);
				} else {
					node = node.RightChild;
					currentIndex += (Count(node == null ? null : node.LeftChild) + 1);
				}
			}

			return null;
		}

		public Node Merge(Node left, Node right)
		{
			if (left == null || right == null) {
				return left == null ? right : left;
			}

			if ((double)Count(left) / (double)(Count(left) + Count(right)) > random_.NextDouble()) {
				left.RightChild = Merge(left.RightChild, right);
				return Update(left);
			} else {
				right.LeftChild = Merge(left, right.LeftChild);
				return Update(right);
			}
		}

		public Splited Split(Node node, int k)
		{
			if (node == null) {
				return new Splited(null, null);
			}

			//[0, k), [k, n)
			if (k <= Count(node.LeftChild)) {
				var s = Split(node.LeftChild, k);
				node.LeftChild = s.Right;
				return new Splited(s.Left, Update(node));
			} else {
				var s = Split(node.RightChild, k - Count(node.LeftChild) - 1);
				node.RightChild = s.Left;
				return new Splited(Update(node), s.Right);
			}
		}

		public int UpperBound(Node node, T value)
		{
			if (node == null) {
				return -1;
			}

			var ret = 0;
			while (node != null) {
				if (comparer_.Compare(node.Value, value) > 0) {
					node = node?.LeftChild;
				} else {
					ret += Count(node?.LeftChild) + 1;
					node = node?.RightChild;
				}
			}

			return ret;
		}

		public T UpperBoundValue(Node node, T value)
		{
			T ret = inf_;
			while (node != null) {
				if (comparer_.Compare(node.Value, value) > 0) {
					ret = node.Value;
					node = node?.LeftChild;
				} else {
					node = node?.RightChild;
				}
			}

			return ret;
		}

		public int LowerBound(Node node, T value)
		{
			if (node == null) {
				return -1;
			}

			var ret = 0;
			while (node != null) {
				if (comparer_.Compare(node.Value, value) >= 0) {
					node = node?.LeftChild;
				} else {
					ret += Count(node?.LeftChild) + 1;
					node = node?.RightChild;
				}
			}

			return ret;
		}

		public T LowerBoundValue(Node node, T value)
		{
			T ret = inf_;
			while (node != null) {
				if (comparer_.Compare(node.Value, value) >= 0) {
					ret = node.Value;
					node = node?.LeftChild;
				} else {
					node = node?.RightChild;
				}
			}

			return ret;
		}

		private Node Update(Node node)
		{
			node.SubTreeSize = Count(node.LeftChild) + Count(node.RightChild) + 1;
			return node;
		}

		public IEnumerable<T> Enumerate(Node node)
		{
			var ret = new List<T>();
			Enumerate(node, ret);
			return ret;
		}

		private void Enumerate(Node node, List<T> ret)
		{
			if (node == null) {
				return;
			}

			Enumerate(node.LeftChild, ret);
			ret.Add(node.Value);
			Enumerate(node.RightChild, ret);
		}

		public class Node
		{
			public T Value { get; set; }
			public Node LeftChild { get; set; }
			public Node RightChild { get; set; }
			public int SubTreeSize { get; set; }
			public Node(T value)
			{
				Value = value;
				SubTreeSize = 1;
			}
		}

		public class Splited
		{
			public Node Left { get; set; }
			public Node Right { get; set; }
			public Splited(Node left, Node right)
			{
				Left = left;
				Right = right;
			}
		}
	}

	public class PriorityQueue<T>
	{
		private readonly List<T> heap_;
		private readonly Comparison<T> comparison_;
		private readonly bool reverses_;

		public T Top => heap_[0];
		public int Count => heap_.Count;

		public PriorityQueue(bool reverses = false)
			: this(Comparer<T>.Default, reverses) { }

		public PriorityQueue(int capacity, bool reverses = false)
			: this(capacity, Comparer<T>.Default.Compare, reverses) { }

		public PriorityQueue(IComparer<T> comparer, bool reverses = false)
			: this(16, comparer.Compare, reverses) { }

		public PriorityQueue(Comparison<T> comparison, bool reverses = false)
			: this(16, comparison, reverses) { }

		public PriorityQueue(
			int capacity,
			Comparison<T> comparison,
			bool reverses = false)
		{
			heap_ = new List<T>(capacity);
			comparison_ = comparison;
			reverses_ = reverses;
		}

		public void Enqueue(T item)
		{
			int c = heap_.Count;
			heap_.Add(item);
			while (c > 0) {
				int p = (c - 1) >> 1;
				if (Compare(p, c) < 0) {
					Swap(p, c);
				} else {
					break;
				}

				c = p;
			}
		}

		public T Dequeue()
		{
			T ret = heap_[0];
			int n = heap_.Count - 1;

			heap_[0] = heap_[n];
			heap_.RemoveAt(n);
			for (int p = 0, c; (c = (p << 1) + 1) < n; p = c) {
				if (c != n - 1 && Compare(c + 1, c) > 0) {
					++c;
				}

				if (Compare(p, c) < 0) {
					Swap(p, c);
				} else {
					break;
				}
			}

			return ret;
		}

		public void Clear() => heap_.Clear();

		private int Compare(int x, int y)
			=> comparison_(heap_[x], heap_[y]) * (reverses_ ? -1 : 1);

		private void Swap(int x, int y)
		{
			var t = heap_[x];
			heap_[x] = heap_[y];
			heap_[y] = t;
		}
	}

	public static class Helper
	{
		public static void UpdateMin32<T>(T array, int index, int value) where T : IList<int>
			=> array[index] = Math.Min(array[index], value);
		public static void UpdateMax32<T>(T array, int index, int value) where T : IList<int>
			=> array[index] = Math.Max(array[index], value);
		public static void UpdateMin64<T>(T array, int index, long value) where T : IList<long>
			=> array[index] = Math.Min(array[index], value);
		public static void UpdateMax64<T>(T array, int index, long value) where T : IList<long>
			=> array[index] = Math.Max(array[index], value);

		public static T[] Array<T>(int n, Func<int, T> init)
			=> Enumerable.Range(0, n).Select(x => init(x)).ToArray();
		public static List<T> List<T>(int n, Func<int, T> init)
			=> Enumerable.Range(0, n).Select(x => init(x)).ToList();
	}

	public class Scanner2
	{
		private readonly char[] delimiter_ = new char[] { ' ' };
		private readonly string filePath_;
		private readonly Func<string> reader_;
		private string[] buf_;
		private int index_;

		public Scanner2(string file = "")
		{
			if (string.IsNullOrWhiteSpace(file)) {
				reader_ = Console.ReadLine;
			} else {
				filePath_ = file;
				var fs = new StreamReader(file);
				reader_ = fs.ReadLine;
			}
			buf_ = new string[0];
			index_ = 0;
		}

		public string Next()
		{
			if (index_ < buf_.Length) {
				return buf_[index_++];
			}

			string st = reader_();
			while (st == "") {
				st = reader_();
			}

			buf_ = st.Split(delimiter_, StringSplitOptions.RemoveEmptyEntries);
			if (buf_.Length == 0) {
				return Next();
			}

			index_ = 0;
			return buf_[index_++];
		}

		public int Int() => int.Parse(Next());
		public long Long() => long.Parse(Next());
		public double Double() => double.Parse(Next());

		public int[] ArrayInt(int N, int add = 0)
		{
			int[] Array = new int[N];
			for (int i = 0; i < N; i++) {
				Array[i] = Int() + add;
			}
			return Array;
		}

		public long[] ArrayLong(int N, long add = 0)
		{
			long[] Array = new long[N];
			for (int i = 0; i < N; i++) {
				Array[i] = Long() + add;
			}
			return Array;
		}

		public double[] ArrayDouble(int N, double add = 0)
		{
			double[] Array = new double[N];
			for (int i = 0; i < N; i++) {
				Array[i] = Double() + add;
			}
			return Array;
		}

		public void Save(string text)
		{
			if (string.IsNullOrWhiteSpace(filePath_)) {
				return;
			}

			File.WriteAllText(filePath_ + "_output.txt", text);
		}
	}
}