Problem:


Score : 400 points

Problem Statement

You are given N integers; the i-th of them is A_i.
Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like.

Constraints

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the maximum possible sum of the absolute differences between the adjacent elements after arranging the given integers in a row in any order you like.

Sample Input 1

5
6
8
1
2
3

Sample Output 1

21

When the integers are arranged as 3,8,1,6,2, the sum of the absolute differences between the adjacent elements is |3 - 8| + |8 - 1| + |1 - 6| + |6 - 2| = 21. This is the maximum possible sum.

Sample Input 2

6
3
1
4
1
5
9

Sample Output 2

25

Sample Input 3

3
5
5
1

Sample Output 3

8



Sample input:
5
6
8
1
2
3


Sample output:
21

Submission status: Wrong Answer

Solution code:
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(n=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(n+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, n+1, i): is_prime[j] = False
    return [i for i in range(n+1) if is_prime[i]]
def prime_factor(n):
    """Return a list of prime factorization numbers of n"""
    res = []
    for i in range(2,int(n**0.5)+1):
        while n%i==0: res.append(i); n //= i
    if n != 1: res.append(n)
    return res
## const ##
MOD=10**9+7
## libs ##
import itertools as it
import functools as ft
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#
def main():
    n = II()
    aa = [II() for _ in range(n)]
    aa.sort()
    dq = deque(aa)
    dq2 = deque()
    front = False
    minf = True
    while dq:
        if minf:
            d = dq.popleft()
            if front:
                dq2.appendleft(d)
                front = not front
            else:
                dq2.append(d)
                front = not front
                minf = not minf
        else:
            d = dq.pop()
            if front:
                dq2.appendleft(d)
                front = not front
            else:
                dq2.append(d)
                front = not front
                minf = not minf
    ans = 0
    dq2 = list(dq2)
    for i in range(n-1):
        ans += abs(dq2[i]-dq2[i+1])
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


def main():
    N = int(input())
    A = [int(input()) for _ in range(N)]
    A.sort()

    if N == 2:
        print(abs(A[0] - A[1]))
        return
    elif N == 3:
        print(A[2] + A[1] - 2 * A[0])
        return

    if N % 2 == 0:
        ans = A[N // 2] - A[N // 2 - 1]
    else:
        ans = -A[N // 2] - A[N // 2 - 1]

    for i in range(N // 2 - 1):
        ans -= 2 * A[i]
    for i in range(N // 2 + 1, N):
        ans += 2 * A[i]

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def resolve():
    '''
    code here
    '''
    import collections
    N = int(input())
    A_list = [int(input()) for _ in range(N)]
    A_odered = collections.deque(sorted(A_list))
    res_list = collections.deque([A_odered.popleft()])
    res_list.appendleft(A_odered.pop())
    res = abs(res_list[0] - res_list[1])

    while len(A_odered) >= 1:
        temp_def1 = abs(res_list[0] - A_odered[0])
        temp_def2 = abs(res_list[-1] - A_odered[-1])

        if temp_def1 >= temp_def2:
            add_num = A_odered.popleft()
            res += temp_def1
            res_list.appendleft(add_num)
        else:
            add_num = A_odered.pop()
            res +=temp_def2
            res_list.append(add_num)
    # print(res_list)
    print(res)
if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

Solution code:
def resolve():
    '''
    code here
    '''
    import collections
    N = int(input())
    A_list = [int(input()) for _ in range(N)]
    A_odered = collections.deque(sorted(A_list))
    res_list = collections.deque([A_odered.popleft()])

    while len(A_odered) >= 1:
        res_list.appendleft(A_odered.pop())
        if len(A_odered) >=1:
            res_list.append(A_odered.pop())
        if len(A_odered) >=1:
            res_list.appendleft(A_odered.popleft())
        if len(A_odered) >=1:
            res_list.append(A_odered.popleft())

    # print(res_list)
    res = 0
    prev = 0
    for i in res_list:
        if prev == 0:
            pass
        else:
            res += abs(i - prev)

        prev = i

    print(res)
if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

Solution code:
def resolve():
    '''
    code here
    '''
    import collections
    N = int(input())
    A_list = [int(input()) for _ in range(N)]
    A_odered = collections.deque(sorted(A_list))
    res_list = collections.deque([A_odered.popleft()])

    while len(A_odered) >= 1:
        res_list.appendleft(A_odered.pop())
        if len(A_odered) >=1:
            res_list.append(A_odered.pop())
        if len(A_odered) >=1:
            res_list.appendleft(A_odered.popleft())
        if len(A_odered) >=1:
            res_list.append(A_odered.popleft())

    res = 0
    prev = 0
    for i in res_list:
        if prev == 0:
            pass
        else:
            res += abs(i - prev)

        prev = i

    print(res)
if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

Solution code:
def resolve():
    '''
    code here
    '''
    import collections
    N = int(input())
    A_list = [int(input()) for _ in range(N)]
    A_odered = collections.deque(sorted(A_list))
    res_list = collections.deque([A_odered.popleft()])

    while len(A_odered) >= 1:
        res_list.append(A_odered.pop())
        if len(A_odered) >=1:
            res_list.appendleft(A_odered.pop())
        if len(A_odered) >=1:
            res_list.append(A_odered.popleft())
        if len(A_odered) >=1:
            res_list.appendleft(A_odered.popleft())

    res = 0
    prev = 0
    for i in res_list:
        if prev == 0:
            pass
        else:
            res += abs(i - prev)

        prev = i
        
    print(res)
if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
A = [INT() for _ in range(N)]
A.sort()
A = deque(A)

l = deque([])
l.append(A.popleft())

while A:
	l.appendleft(A.pop())
	if not A:
		break
	l.append(A.pop())
	if not A:
		break
	l.appendleft(A.popleft())
	if not A:
		break
	l.append(A.popleft())

l = list(l)
ans = 0
for i in range(1, N):
	ans += abs(l[i-1]-l[i])
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
X = [int(input()) for _ in range(N)]
X.sort()
if N == 3:
    # a, b, c
    # b = min
    # a + c - 2 * b = (a + b + c) - 3 * b
    print(sum(X) - min(X) * 3)
elif N & 1:
    lower = X[: N // 2 + 1]  # n+1個
    upper = X[N // 2 + 1:]  # n個
    num = len(upper) - 1
    x = 2 * sum(upper)
    y = sum(lower) + sum(lower[:num])
    print(x - y)
else:
    lower = X[:N // 2]
    upper = X[N // 2:]
    x = 2 * sum(upper) - upper[0]
    y = 2 * sum(lower) - lower[-1]
    print(x - y)

Submission status: Wrong Answer

Solution code:
N = int(input())
X = [int(input()) for _ in range(N)]
X.sort()
if N == 3:
    # a, b, c
    # b = min
    # a + c - 2 * b = (a + b + c) - 3 * b
    print(sum(X) - min(X) * 3)
elif N & 1:
    lower = X[: N // 2 + 1]  # n+1個
    upper = X[N // 2 + 1:]  # n個
    num = len(upper) - 1
    x = 2 * sum(upper)
    y = sum(lower) + sum(lower[:num])
    print(lower, sum(lower[:num]))
    print(x - y)
else:
    lower = X[:N // 2]
    upper = X[N // 2:]
    print(lower)
    print(upper)
    x = 2 * sum(upper) - upper[0]
    y = 2 * sum(lower) - lower[-1]
    print(x - y)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline

n = int(input())
a = list(int(input()) for i in range(n))

a.sort()
if n%2==0:
    start = n//2-1
    left = 0
    right = n-1
    ans0 = abs(a[right]- a[start])
    while start != left:
        ans0+=abs(a[left]-a[right])
        right -= 1
        ans0+=abs(a[right]-a[left])
        left += 1

    start = n//2
    left = 0
    right = n-1
    ans1 = abs(a[left]- a[start])
    while start != right:
        ans1+=abs(a[right]-a[left])
        left += 1
        ans1+=abs(a[left]-a[right])
        right -= 1

    ans = max(ans0,ans1)
    print(ans)

if n%2==1:
    start = n//2
    left = 0
    right = n-1
    ans0 = abs(a[right]- a[start])
    while True:
        ans0+=abs(a[left]-a[right])
        right -= 1
        if start == right: break
        ans0+=abs(a[right]-a[left])
        left += 1


    left = 0
    right = n-1
    ans1 = abs(a[left]- a[start])
    while True:
        ans1+=abs(a[right]-a[left])
        right -= 1
        if start == right: break
        ans1+=abs(a[left]-a[right])
        left += 1

    ans = max(ans0,ans1)
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline

n = int(input())
a = list(int(input()) for i in range(n))

a.sort()
if n%2==0:
    start = n//2-1
    left = 0
    right = n-1
    ans = abs(a[right]- a[start])
    while start != left:
        ans+=abs(a[left]-a[right])
        right -= 1
        ans+=abs(a[right]-a[left])
        left += 1

    print(ans)
    exit()

if n%2==1:
    start = n//2
    left = 0
    right = n-1
    ans0 = abs(a[right]- a[start])
    while True:
        ans0+=abs(a[left]-a[right])
        right -= 1
        if start == right: break
        ans0+=abs(a[right]-a[left])
        left += 1


    left = 0
    right = n-1
    ans1 = abs(a[left]- a[start])
    while True:
        ans1+=abs(a[right]-a[left])
        right -= 1
        if start == right: break
        ans1+=abs(a[left]-a[right])
        left += 1

    ans = max(ans0,ans1)

    print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = [int(input()) for _ in range(N)]
A.sort()
M = (N + 1) // 2 - 1

s = 0
for i in range(M):
    s += abs(A[i] - A[N - 1 - i])

for i in range(M):
    s += abs(A[i] - A[N - 2 - i])

s += abs(A[N - 1] - A[M])
print(s)

Submission status: Wrong Answer

Solution code:
from collections import deque
n=int(input())
a=[int(input()) for _ in range(n)]
a.sort()
a=deque(a)
max1=a.pop()
l,r=max1,max1
ans=0
c=0
while len(a)>0:
  if c%2==0:
    m=a.popleft()
  else:
    m=a.pop()
  if abs(l-m)>abs(r-m):
    ans+=abs(l-m)
    l=m
  else:
    ans+=abs(r-m)
    r=m
  c+=1
print(ans)

Submission status: Wrong Answer

Solution code:
def next_a_ind(a_ind):
    if a_ind<0 and a_ind%2==1:
        a_ind-=1
    elif a_ind<0 and a_ind%2==0:
        a_ind*=-1
        a_ind-=1
    elif a_ind>0 and a_ind%2==1:
        a_ind+=1
    else:
        a_ind+=1
        a_ind*=-1
    return a_ind

def next_lis_ind(lis_ind):
    if lis_ind>0:
        lis_ind*=-1
    else:
        lis_ind*=-1
        lis_ind+=1
    return lis_ind

def answer(lis):
    cnt=0
    for i in range(len(lis)-1):
        cnt+=abs(lis[i]-lis[i+1])
    return cnt

import sys
input=sys.stdin.readline
n=int(input())
a=[int(input()) for i in range(n)]
import collections

if n%2==1:
    a=sorted(a)
    lis=[0]*n
    lis[n//2]=a[0]

    cnt=1
    a_ind=-1
    lis_ind=1
    while cnt<n:
        lis[n//2+lis_ind]=a[a_ind]
        a_ind=next_a_ind(a_ind)
        lis_ind=next_lis_ind(lis_ind)
        cnt+=1
        
    print(answer(lis))

else:
    ans=0
    lis=[]
    lis1=[]
    lis2=[]
    lis3=[]
    a=sorted(a)
    a1=a[:n//2]
    a2=a[n//2:]
    
    for x,y in zip(a1,a2):
        lis.append(x)
        lis.append(y)
        lis1.append(y)
        lis1.append(x)

    ans=max(answer(lis),answer(lis1))
    
    a2=a2[::-1]
    
    for x,y in zip(a1,a2):
        lis2.append(x)
        lis2.append(y)
        lis3.append(y)
        lis3.append(x)
    
    ans=max(answer(lis2),answer(lis3),ans)
    print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
ai = [int(input()) for i in range(n)]

ai.sort()

deq = deque()
deq.appendleft(ai[0])

#print(ai)
#print()

for i in range(n-1):
    if i % 4 == 0:
        deq.appendleft(ai[n-i//2-1])
        #print(n-i//2-1)
    elif i % 4 == 1:
        deq.append(ai[n-i//2-2])
        #print(n-i//2-2)
    elif i % 4 == 2:
        deq.appendleft(ai[i//2])
        #print(i//2)
    elif i % 4 == 3:
        deq.append(ai[i//2+1])
        #print(i//2+1)
        #print(n-i//3-2)
    #print(deq)
    
ans = 0

for i in range(n-1):
    ans += abs(deq[i+1] - deq[i])
    
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
ai = [int(input()) for i in range(n)]

ai.sort()

deq = deque()
deq.appendleft(ai[0])

#print(ai)

for i in range(n-1):
    if i % 4 == 0:
        deq.appendleft(ai[n-i//2-1])
    elif i % 4 == 1:
        deq.append(ai[n-i//2-2])
    elif i % 4 == 2:
        deq.appendleft(ai[i-1])
    elif i % 4 == 3:
        deq.append(ai[i-1])
        #print(n-i//3-2)
    #print(deq)
    
ans = 0

for i in range(n-1):
    ans += abs(deq[i+1] - deq[i])
    
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = sorted([int(input()) for _ in range(N)], reverse=True)
result = 0
if N % 2 == 0:
    k = [2]*((N-2)//2)
    k += [1]
    k += [-1]
    a = [-2]*((N-2)//2)
    k = k+a
else:
    k = [2]*(N//2-1)
    k += [1]
    k += [1]
    a = [-2]*(N//2)
    k = k+a
for a, keisu in zip(A, k):
    result += a*keisu
print(result)

Submission status: Wrong Answer

Solution code:
# https://atcoder.jp/contests/tenka1-2018-beginner/tasks/tenka1_2018_c

from collections import deque

n = int(input())
A = [int(input()) for _ in range(n)]
A.sort()
A = deque(A)
ans = deque([])

# print(n, A)

# (1) 左右で差が最大の方にくっつけるgreedy
is_left = True
while len(A) > 0:
    value = A.popleft() if is_left else A.pop()

    if len(ans) == 0:
        ans.append(value)
    else:
        vleft, vright = ans[0], ans[-1]
        if abs(vleft - value) > abs(vright - value):
            ans.appendleft(value)
        else:
            ans.append(value)
    is_left = not is_left

total_diff = 0
for i in range(n - 1):
    total_diff += abs(ans[i] - ans[i + 1])
# print(ans)
print(total_diff)

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
a = [int(input()) for _ in range(n)]
a.sort()
a = deque(a)
mi, ma = a.popleft(), a.pop()
ans = ma - mi
switch = 0
for i in range((n-2)//2):
    l, r = a.popleft(), a.pop()
    if switch:
        ans += abs(mi - l)
        ans += abs(ma - r)
        mi, ma = l, r
        switch = 0
    else:
        ans += abs(mi - r)
        ans += abs(ma - l)
        mi, ma = r, l
        switch = 1
if a: ans += abs(a[0] - mi)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value

N = ii()
A = sorted([ii() for _ in range(N)])
'''
if N > 2:
    ans += A[-1] * 2 - A[0] - A[1]
    l_ind = 2
    r_ind = N-2
    while True:
        if r_ind - 2 >= l_ind:
'''
if N==3:
    print(max(A[2]+A[1]-A[0]*2, A[2]*2-A[1]-A[0]))
elif N%2:
    ans_1 = A[N-1]*2 - A[0] - A[1]
    ans_1 += sum(A[N//2:N-1]) - sum(A[:N//2])
    ans_2 = A[N-1] + A[N-2] - A[0]*2
    ans_2 += sum(A[N//2+1:]) - sum(A[1:N//2+1])
    print(max(ans_1, ans_2))
else:
    ans_1 = A[N-1]*2 - A[0] - A[1]
    ans_1 += sum(A[N//2:N-1]) - sum(A[:N//2-1])
    ans_1 + A[N//2] - A[N//2]
    ans_2 = A[N-1] + A[N-2] - A[0]*2
    ans_2 += sum(A[N//2+1:]) - sum(A[1:N//2])
    ans_2 += A[N//2] - A[N//2-2]
    print(max(ans_1, ans_2))

Submission status: Wrong Answer

Solution code:
from collections import deque
import copy
import sys

sys.setrecursionlimit(10**6)

def solve(idx, arr, lcur, rcur, isL):
  if len(idx) == len(arr):
    return sum([abs(arr[idx[i]]-arr[idx[i-1]]) for i in range(1, len(idx))])
  else:
    fL = copy.copy(idx)
    fR = copy.copy(idx)
    if isL:
      if lcur <= rcur:
        fL.appendleft(lcur)
        fR.append(lcur)
        lcur += 1
        if lcur <= rcur:
          fL.append(lcur)
          fR.appendleft(lcur)
          lcur += 1
    else:
      if lcur <= rcur:
        fL.appendleft(rcur)
        fR.append(rcur)
        rcur -= 1
        if lcur <= rcur:
          fL.append(rcur)
          fR.appendleft(rcur)
          rcur -= 1
    return max(solve(fL, arr, lcur, rcur, not isL), solve(fR, arr, lcur, rcur, not isL))

N = int(input())
A = sorted([int(input()) for _ in range(N)])
print(solve(deque([0]), A, 1, N-1, False))

Submission status: Wrong Answer

Solution code:
import collections
N = int(input())
A = []
for i in range(N):
    A.append(int(input()))
A.sort()

s = collections.deque([A[0]])
ans = 0
i = 1
j = N-1
while i <= j:
    if len(s) % 2:
        x = A[j]
        j -= 1
    else:
        x = A[i]
        i += 1
    if abs(s[0]-x) > abs(s[-1]-x):
        s.appendleft(x)
    else:
        s.append(x)
assert len(s) == N
ans = 0
for i in range(1, N):
    ans += abs(s[i] - s[i-1])
print(ans)

Submission status: Wrong Answer

Solution code:
#Tenka1 Programmer Beginner Contest-C Align
"""
リストを並び替えて隣り合う要素の差の最大を出力
"""
import sys
from collections import deque
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

n = int(readline())
lst1 = []
for i in range(n):
    lst1.append(int(readline()))

d = deque()

lst1.sort()
lst2 = lst1[:n//2] #小さい方
lst1 = lst1[n//2:] #大きい方
large = deque(lst1)
small = deque(lst2)
#2又に分かれるまで手動
res1 = large.pop()
res2 = small.popleft()
def func(x):
    global res1,res2
    if abs(res1-x) > abs(res2-x):
        res = abs(res1-x)
        res1 = x
        return res
    else:
        res = abs(res2-x)
        res2 = x
        return res

ans = res1-res2
if not len(small):
    pass
else:
    res3 = small.popleft()
    ans += func(res3)
while True:
    if not len(large):
        pass
    else:
        ans += func(large.pop())
    if not len(large):
        pass
    else:
        ans += func(large.pop())
    if not len(small):
        pass
    else:
        ans += func(small.popleft())
    if not len(small):
        pass
    else:
        ans += func(small.popleft())
    if not (len(large) or len(small)):
        print(ans)
        exit()

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

from collections import deque

n = int(readline())
a = sorted([int(readline()) for i in range(n)])
b = deque(a[n // 2:])
a = deque(a[:n // 2])
ans = deque([a.popleft()])
for i in range(n // 2):
    if i % 2 == 0:
        ans.appendleft(b.pop())
        if len(b) == 0:
            if len(a) != 0:
                ans.append(a.popleft())
            break
        ans.append(b.pop())
    else:
        ans.appendleft(a.popleft())
        if len(a) == 0:
            if len(b) != 0:
                ans.append(b.pop())
            break
        ans.append(a.popleft())
cnt = 0
for i in range(1, n):
    cnt += abs(ans[i - 1] - ans[i])
print(cnt)

Submission status: Wrong Answer

Solution code:
N  = int (input())
As = [int(input()) for _ in range(N)]
# print(As)
As.sort()


bottom_ind = 1
upper_ind = N - 1

l = r = As[0]

MA = 1
MI = 0
mode = MA



ans = 0
while True:
    if mode == MA: #上から取る
        next1 = As[upper_ind]
        next2 = As[upper_ind -1]
        ans += max(abs(next1 - l ) + abs(next2 - r ),abs(next2 - r ) + abs(next1 - l ))
        r =  next1
        l = next2
        m = upper_ind  - 2
        upper_ind -= 2
        mode = MI

    else:
        next1 = As[bottom_ind]
        next2 = As[bottom_ind + 1]
        ans += max(abs(next1 - l) + abs(next2 - r), abs(next2 - r) + abs(next1 - l))
        m = bottom_ind + 2
        bottom_ind+= 2
        r = next1
        l = next2
        mode = MA #下から取る
    if bottom_ind >= upper_ind:
        break
if N % 2 == 0:
    # m = As[N//2]
    m = As[m]
    ans += max( abs(m - l) ,abs(m - r))
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
L = [int(input()) for _ in range(N)]


if N % 2 == 1:
    L = sorted(L, reverse=True)
    minority = N//2
    majority = N - minority
    A = sum(L[:minority])*2 - sum(L[minority:])*2+sum(L[minority:minority+2])
    B = sum(L[:majority])*2 - sum(L[majority:])*2 - sum(L[majority-2:majority])
    ans = max(A, B)
else:
    L = sorted(L)
    C = sum(L[:N//2])*2 - sum(L[N//2:])*2 + L[N//2]-L[N//2-1]
    D = C
    ans = max(C, D)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
A = []
for i in range(n):
    A.append(int(input()))
A = sorted(A)

B = A[:n//2]
C = A[n//2:][::-1]
D = []
if len(B) < len(C):
    B = A[:n//2+1]
    C = A[n//2+1:][::-1]
    D.append(B[0])
    B = B[1:]
    t = 0
    for i in range(len(B)):
        if t == 0:
            D = [B[i]] + [C[i]] + D
            t += 1
        else:
            D.append(C[i])
            D.append(B[i])
    ans = 0
    for i in range(n - 1):
        ans += abs(D[i] - D[i+1])
    print(ans)

else:
    t = 0
    D.append(B[0])
    B = B[1:]
    for i in range(len(B)):
        if t == 0:
            D = [B[i]] + [C[i]] + D
            t += 1
        else:
            D.append(C[i])
            D.append(B[i])
    D = [C[-1]] + D
    ans = 0
    for i in range(n - 1):
        ans += abs(D[i] - D[i+1])
    print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
A = [int(input()) for _ in range(N)]
A.sort()
d = deque(A)

#print(d)

ans = []

for i in range(N):
    x = d.pop() if i % 2 == 0 else d.popleft()
    ans.append(x)


def amount(array):
    ret = 0
    for i in range(N-1):
        ret += abs(array[i+1]-array[i])
    return ret

ret = amount(ans)    
x = ans.pop()
ans = [x] + ans
#print(ans)

ret = max(ret, amount(ans))

print(ret)

Submission status: Wrong Answer

Solution code:
from sys import stdin
N = int(stdin.readline().rstrip())
A = []
for i in range(N):
    A.append(int(input()))

A.sort()

ans = 0
if N % 2 == 0:
    tmp = [-1,1] + [2]*((N-2)//2) + [-2]*((N-2)//2)
    for i,j in zip(sorted(tmp),A):
        ans += (i*j)
    print(ans)
else:
    tmp = [-1,-1] + [2]*((N-1)//2) + [-2]*((N-2)//2)
    for i,j in zip(sorted(tmp),A):
        ans += (i*j)
    print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
N = int(stdin.readline().rstrip())
A = []
for i in range(N):
    A.append(int(input()))

A.sort()

ans = 0
if N % 2 == 0:
    tmp = [-1,1] + [2]*((N-2)//2) + [-2]*((N-2)//2)
    for i,j in zip(sorted(tmp),A):
        ans += (i*j)
    print(ans)
else:
    tmp = [-1,1] + [2]*((N-1)//2) + [-2]*((N-2)//2)
    for i,j in zip(sorted(tmp),A):
        ans += (i*j)
    print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = 1e10

#solve
def solve():
    n = II()
    a = IR(n)
    a.sort()
    q = deque(a)
    p = q.popleft()
    ans = deque([p])
    for i in range(n-1):
        if i % 4 in [2, 3]:
            p = q.popleft()
        else:
            p = q.pop()
        if i & 1:
            ans.appendleft(p)
        else:
            ans.append(p)
    num = 0
    for i in range(n - 1):
        num += abs(ans[i + 1] - ans[i])
    print(num)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from collections import deque
N = int(input())
Alist = deque(sorted([int(input()) for _ in range(N)]))
ans = 0
right = True
mae = [Alist.popleft()] * 2
while Alist:
    if right:
        now = [Alist.pop()]
        if Alist:
            now.append(Alist.pop())
            ans += abs(sum(mae) - sum(now))
        else:
            ans += abs(min(mae) - now[0])
    else:
        now = [Alist.popleft()]
        if Alist:
            now.append(Alist.popleft())
            ans += abs(sum(mae) - sum(now))
        else:
            ans += abs(max(mae) - now[0])
    mae = now
    right = not right
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    N, *A = map(int, open(0).read().split())
    A.sort()
    if N % 2 == 0:
        s, l = A[:N//2], A[N//2:]
        ans = 2*(sum(l) - sum(s))
        ans += s[-1] - l[0]
        print(ans)
        return

    sep1 = (N + 1)//2
    s1, l1 = A[:sep1], A[sep1:]
    # print(s1, l1)
    ans1 = 2*abs(sum(l1) - sum(s1))
    ans1 += s1[-1] + s1[-2]

    sep2 = sep1 - 1
    s2, l2 = A[:sep2], A[sep2:]
    # print(s2, l2)
    ans2 = 2*abs(sum(l2) - sum(s2))
    ans2 -= l2[0] + l2[1]

    print(max(ans1, ans2))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    N, *A = map(int, open(0).read().split())
    A.sort()
    if N % 2 == 0:
        s, l = A[:N//2], A[N//2:]
        ans = 2*(sum(l) - sum(s))
        ans += s[-1] - l[0]
        print(ans)
        return

    sep1 = (N + 1)//2
    s1, l1 = A[:sep1], A[sep1:]
    # print(s1, l1)
    ans1 = 2*abs(sum(l1) - sum(s1))
    ans1 += s1[-1] + s1[-2]

    sep2 = sep1 - 1
    s2, l2 = A[:sep2], A[sep2:]
    # print(s2, l2)
    ans2 = 2*abs(sum(l2) - sum(s2))
    ans2 -= l2[0] + l2[1]

    print(ans1, ans2)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def main():
    N, *A = map(int, open(0).read().split())
    A.sort()
    if N == 2:
        print(A[1] - A[0])
        return
    sep = (N + 1)//2
    s, l = A[:sep], A[sep:]
    # print(s, l)
    ans = 2*(sum(l) - sum(s))
    if ans < 0:
        ans *= -1
    if N % 2 == 0:
        ans += s[-1] - l[0]
    else:
        ans += s[-1] + s[-2]
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from math import ceil
from itertools import permutations


def main():
    length = int(input())
    numbers = [int(input()) for _ in range(length)]
    numbers.sort()
    number_pair = []
    for i in range(ceil(length / 2) - 1):
        number_pair.append([numbers[i], numbers[-i - 1]])
    number_pair.sort(key=lambda x: x[1])
    side = [numbers[length // 2]]
    if length % 2 == 0:
        side.append(numbers[length // 2 - 1])
    else:
        side.append(-1)
    answer = 0
    if 2 < length:
        for left_side, right_side in permutations(side):
            large_first = 0
            small_first = 0
            for i in range(len(number_pair)):
                if i == 0 and left_side != -1:
                    large_first += abs(left_side - number_pair[i][1])
                    small_first += abs(left_side - number_pair[i][0])
                elif i == len(number_pair) - 1 and right_side != -1:
                    large_first += abs(right_side - number_pair[i][0])
                    small_first += abs(right_side - number_pair[i][1])
                if 0 < i:
                    large_first += abs(number_pair[i][1] - number_pair[i - 1][0])
                    small_first += abs(number_pair[i][0] - number_pair[i - 1][1])
                large_first += abs(number_pair[i][0] - number_pair[i][1])
                small_first += abs(number_pair[i][0] - number_pair[i][1])
            answer = max(answer, large_first, small_first)
    else:
        answer = abs(numbers[0] - numbers[1])
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque

n=int(input())
a=[int(input()) for _ in range(n)]
a.sort()
d=deque()
d.append(a[0])
d.append(a[-1])
b=[False]*n
b[0]=True
b[-1]=True

for i in range(1,n-1):
    if b[i] is False:
        if abs(a[i]-d[0])>abs(a[i]-d[-1]):
            d.appendleft(a[i])
        elif abs(a[i]-d[0])<abs(a[i]-d[-1]):
            d.append(a[i])
        else:
            if d[0]>d[-1]:
                d.appendleft(a[i])
            else:
                d.append(a[i])
        b[i]=True
    else:
        break

    if b[-1-i] is False:
        if abs(a[-1-i]-d[0])>abs(a[-1-i]-d[-1]):
            d.appendleft(a[-1-i])
        elif abs(a[i]-d[0])<abs(a[i]-d[-1]):
            d.append(a[-1-i])
        else:
            if d[0]>d[-1]:
                d.append(a[-1-i])
            else:
                d.appendleft(a[-1-i])
        b[-1-i]=True
    else:
        break

ans=0
for i in range(1,n):
    ans+=abs(d[i]-d[i-1])
print(ans)