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: Accepted

Solution code:
N = int(input())
A = [int(input()) for i in range(N)]

A_ = sorted(A)
A_r = list(reversed(A_))

n = (A_[0], A_r[0])
sum = abs(n[0] - n[1])
for i, (x, y) in enumerate(zip(A_[1:N//2], A_r[1:N//2])):
    sum += abs(n[0] - y) + abs(n[1] - x)
    n = (x, y)

if N%2 != 0:
    m = A_[N//2]
    sum += max(abs(n[0] - m), abs(n[1] - m))

print(sum)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(input()) for i in range(N)]

A.sort()

if len(A) % 2 == 1:
    order1 = [-1, -1]
    for i in range(len(A)-2):
        if i % 2 == 0:
            order1.append(2)
        else:
            order1.append(-2)

    order2 = [1, 1]
    for i in range(len(A)-2):
        if i % 2 == 0:
            order2.append(-2)
        else:
            order2.append(2)
else:
    order1 = [-1, 1]
    for i in range(len(A) - 2):
        if i % 2 == 0:
            order1.append(2)
        else:
            order1.append(-2)

    order2 = [-1, 1]
    for i in range(len(A) - 2):
        if i % 2 == 0:
            order2.append(-2)
        else:
            order2.append(2)


order1.sort()
order2.sort()

sum1 = 0
sum2 = 0
for x, y, z in zip(A, order1, order2):
    sum1 += x * y
    sum2 += x * z

print(max(sum1, sum2))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

S = int(input())
lis = []
for item in range(0,int(S)):
    tmp = input()
    lis.append(int(tmp))
ls = sorted(lis)
#print(ls)
#print(ls[int(S/2)])
i = 1
lo = 0
hg = int(S)-1
ans2 = 0
if True:#S % 2 == 1 :
    ans =  ls[hg]- ls[int(S/2-0.5)]
    #print(ans)
    for k in range(0,int(S/2)+1):
        #print(i)
    # TODO: write code...
    # TODO: write code...
    # TODO: write code...
        #if(k != 0):
        #    hg-=1
        if(i == int(S)-1):
            break
        ans = ans + ls[hg] - ls[lo]
        i+=1
        #print(ls[hg],ls[lo])
        hg-=1
        #print(i)
        #print(ans)
        if(i == int(S)-1):
            break
        ans = ans + ls[hg] - ls[lo]
        #print(ls[hg],ls[lo])
        lo+=1
        i+=1
        #print(ans)
tmp1 = ans


if S % 2 == 1:
    ls = sorted(lis,reverse=True)
    #print(ls)
    lo = 0
    hg = int(S)-1
    ans2 =  ls[int(S/2)]-ls[hg]
    #print(ans2)
    i = 1
    for k in range(0,int(S/2)+1):
        #print(i)
    # TODO: write code...
    # TODO: write code...
    # TODO: write code...
        #if(k != 0):
        #    hg-=1
        if(i == int(S)-1):
            break
        ans2 = ans2 + ls[lo]-ls[hg]
        i+=1
        #print(ls[hg],ls[lo])
        hg-=1
        #print(i)
        #print(ans)
        if(i == int(S)-1):
            break
        ans2 = ans2 +  ls[lo]-ls[hg]
        #print(ls[hg],ls[lo])
        lo+=1
        i+=1




print(max(ans2,tmp1))
 #   hg-=1
 #   print(ls[hg] , ls[lo])
 #   ans= ans + (ls[hg] - ls[lo])
 #   print(ans)
 #   ans = ans + (ls[hg] - ls[lo])
 #   lo+=1
 #   hg-=1
 #   print(ls[hg] , ls[lo])
 #   print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
n=int(input())
a=[]
for i in range(0,n):
  a.append(int(input()))
a.sort()

l = a[0]
r = a[0]

li=1
ri=len(a)-1

res = 0

while ri>=li:
  ln = abs(l-a[li])
  lx = abs(l-a[ri])
  rn = abs(r-a[li])
  rx = abs(r-a[ri])

  x = max(ln, max(lx, max(rn, rx)))
  
  if x == ln:
    res = res + ln
    l=a[li]
    li=li+1
  elif x == lx:
    res = res + lx
    l=a[ri]
    ri=ri-1
  elif x == rn:
    res = res + rn
    r=a[li]
    li=li+1
  else:
    res = res + rx
    r=a[ri]
    ri=ri-1

print(res)

Submission status: Accepted

Solution code:
N=int(input())
num=[int(input()) for i in range(N)]
num.sort()

if N%2!=0: #kisu
  manaka=int(N/2)  
  sum_a=abs(num[manaka]-num[N-1])
  sum_a+=abs(num[N-1]-num[0])
  for i in range(int((N-1)/2)-1):
    sum_a+=abs(num[N-2-i]-num[i])
    sum_a+=abs(num[i+1]-num[N-2-i])
  sum_b=abs(num[manaka]-num[0])
  sum_b+=abs(num[0]-num[N-1])
  for i in range(int((N-1)/2)-1):
    sum_b+=abs(num[i+1]-num[N-1-i])
    sum_b+=abs(num[i+1]-num[N-2-i])
  print(max(sum_a,sum_b))
else:
  manaka=int(N/2)
  sum=abs(num[manaka]-num[0])
  for i in range(manaka-1):
    sum+=abs(num[i]-num[N-1-i])
    sum+=abs(num[i+1]-num[N-1-i])
  print(sum)

Submission status: Accepted

Solution code:
import sys
iN = int(input())

aA = sorted([int(_) for _ in sys.stdin.readlines()])

#とりあえず公式の解法で解答作りまっす

if iN % 2 == 0:
    iH = iN // 2
    print( -2 * sum(aA[0:iH-1]) - aA[iH-1] + aA[iH] + 2* sum(aA[iH+1:]))
else:
    iH = (iN -1) //2
    iBigStart = -2 * sum(aA[0:iH]) + aA[iH] + aA[iH+1] + 2 * sum(aA[iH+2:])
    iSmallStart = -2 * sum(aA[0:iH-1]) - aA[iH-1] -aA[iH] + 2* sum(aA[iH+1:])
    print(max(iBigStart,iSmallStart))

exit()

Submission status: Accepted

Solution code:
N=int(input())
A=sorted(int(input())for _ in [0]*N)
n=N//2
print(A[n]+2*sum(A[n+1:])-2*sum(A[:n-1])-A[n-1]if N%2==0 else max(A[n]+A[n+1]+2*sum(A[n+2:])-2*sum(A[:n]),2*sum(A[n+1:])-2*sum(A[:n-1])-A[n-1]-A[n]))

Submission status: Accepted

Solution code:
N = int(input())
A =[0]*N
for i in range(N):
    A[i] = int(input())
A.sort(reverse=True)
X=0
Y=0
if N % 2 == 0:
    for i in range(N//2-1):
        X = X + 2*A[i] -2*A[-i-1]
    X = X + A[N//2-1] -A[N//2]
    print(X)    
 
if N % 2 == 1:
        for i in range(N//2):
            X = X + 2 * A[i]
            Y = Y - 2 * A[-i-1]
        for i in range (N//2-1):
            X = X - 2 * A[-i-1]
            Y = Y + 2 * A[i]
        X = X - A[N//2] - A[N//2+1]
        Y = Y + A[N//2-1] + A[N//2]
        print(max(X,Y))

Submission status: Accepted

Solution code:
n=int(input())
a=[]
for i in range(n):
    b=int(input())
    a.append(b)
a.sort()
b=a

if n%2==0:
    for i in range(int(n/2-1)):
        a[int((n/2))+1+i]=2*a[int((n/2))+1+i]
        a[i]=-2*a[i]
    a[int(n/2)-1]=(-1)*a[int(n/2)-1]   
    print(sum(a))
else:
    for i in range(int(n/2)):
        a[int((n/2))+1+i]=2*a[int((n/2))+1+i]
        a[i]=-2*a[i]
    a[int(n/2)]=(-1)*a[int(n/2)]
    a[int(n/2)-1]=a[int(n/2)-1]*0.5     
    c=sum(a)
    
    b[int(n/2)+1]=0.5*b[int(n/2)+1]
    b[int(n/2)]=(-1)*b[int(n/2)]
    b[int(n/2)-1]=2*b[int(n/2)-1]
    d=sum(b)
    print(int(max(c,d)))

Submission status: Accepted

Solution code:
N = int(input())
A_in = [int(input()) for _ in range(N)] 
 
A = sorted(A_in)
res1 = 0
A2 = []
for i in range(len(A)):
    if len(A) == 1:
        if abs(A[0] - A2[0]) < abs(A[0] - A2[-1]):
            A2.append(A[0])
        else:
            A2.insert(0,A[0])
        break
    if i % 2 == 0:
        A2.append(A.pop(-1))
    else:
        A2.append(A.pop(0))
for i in range(len(A2)-1):
    res1 += abs(A2[i] - A2[i+1])

A = sorted(A_in,reverse=True)
res2 = 0
A2 = []
for i in range(len(A)):
    if len(A) == 1:
        if abs(A[0] - A2[0]) < abs(A[0] - A2[-1]):
            A2.append(A[0])
        else:
            A2.insert(0,A[0])
        break
    if i % 2 == 0:
        A2.append(A.pop(-1))
    else:
        A2.append(A.pop(0))
for i in range(len(A2)-1):
    res2 += abs(A2[i] - A2[i+1])

print(max(res1,res2))

Submission status: Accepted

Solution code:
def tpbc_2018_c():
    n = int(input())
    a = [int(input()) for _ in range(n)]
    a.sort()
    low = a[:len(a) // 2]
    high = a[len(a) // 2:]
    if len(a) % 2 == 0:
        return 2 * (sum(high) - sum(low)) + max(low) - min(high)
    else:
        low2 = a[:len(a) // 2 + 1]
        high2 = a[len(a) // 2 + 1:]
        return max(2 * (sum(high) - sum(low)) - high[0]-high[1],2 * (sum(high2) - sum(low2))+low2[-2]+low2[-1])
 
 
print(tpbc_2018_c())

Submission status: Accepted

Solution code:
import copy
N = int(input())
A = [int(input()) for _ in range(N)]
A.sort()
B = copy.deepcopy(A)
sum1 = 0
sum2 = 0
center = -(-N // 2) - 1
if N%2 == 1:
    for i in range(N):
        if i == 0:
            beforeNum = A.pop(center)
        else:
            if i%2 == 1:
                num = A.pop(-1)
            else:
                num = A.pop(0)
            sum1 += abs(beforeNum - num)
            beforeNum = num
    for i in range(N):
        if i == 0:
            beforeNum = B.pop(center)
        else:
            if i%2 == 1:
                num = B.pop(0)
            else:
                num = B.pop(-1)
            sum2 += abs(beforeNum - num)
            beforeNum = num
else:
    for i in range(N):
        if i == 0:
            beforeNum = A.pop(center)
        else:
            if i%2 == 1:
                num = A.pop(-1)
            else:
                num = A.pop(0)
            sum1 += abs(beforeNum - num)
            beforeNum = num
    center = center + 1
    for i in range(N):
        if i == 0:
            beforeNum = B.pop(center)
        else:
            if i%2 == 1:
                num = B.pop(0)
            else:
                num = B.pop(-1)
            sum2 += abs(beforeNum - num)
            beforeNum = num
print(max(sum1,sum2))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

# 終了後、重複処理を整理した版

from collections import deque

N = int(input())
aN = [int(input()) for i in range(N)]

# 受け取ったリストを前後から交互に並べていく
def changeList(_list):
    _list = deque(_list)
    res = [0] * N
    for i in range(N):
        if i % 2 == 0:
            res[i] = _list.popleft()
        else:
            res[i] = _list.pop()
    return res

# 受け取ったリストの隣り合う差の合計、最後だけ先頭とも比べて大きい方
def sumList(_list):
    ans = 0
    for i in range(1,N):
        if i == N-1:
            ans += max(abs(_list[i-1] - _list[i]), abs(_list[i] - _list[0]))
        else:
            ans += abs(_list[i-1] - _list[i])
    return ans

# 昇順と降順、両方試して良かった方を使う
aN2 = changeList(sorted(aN))
aN3 = changeList(sorted(aN, reverse=True))

print(max(sumList(aN2), sumList(aN3)))

Submission status: Accepted

Solution code:
import math as mt
N = int(input())
A = [int(input()) for i in range(N)]
A.sort()
#print(A)
S = 0
P2 = mt.floor(N/2 - 1)
if N % 2 == 0:
    for i in range(0,P2,1):
        S += 2 * (A[N-i-1] - A[i])
    S += A[P2+1] - A[P2]
    print(S)
elif N % 2 == 1:
    for i in range(0,P2,1):
        S += 2 * (A[N-i-1] - A[i])
    S1 = A[N-P2-2] + A[N-P2-1] - 2 * A[P2]
    S2 = 2 * A[N-1-P2] - A[P2] - A[P2+1]
    if S1 >= S2:
        print(S1+S)
    else:
        print(S2+S)

Submission status: Accepted

Solution code:
N=int(input())
inp=[]
for _ in range(N):
    inp.append(int(input()))
inp.sort()

if N%2:
    
    m1=inp[:(N//2+1)]
    M1=inp[(N//2+1):]
    
    m2=inp[:N//2]
    M2=inp[N//2:]
    
    a1=sum(M1)*2-sum(m1)*2+m1[-1]+m1[-2]
    a2=sum(M2)*2-sum(m2)*2-M2[0]-M2[1]
    
    print(max(a1,a2))
    
else:
    
    m=inp[:N//2]
    M=inp[N//2:]
    
    a=sum(M)*2-sum(m)*2+m[-1]-M[0]
    
    print(a)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
n = int(input())
a = []
for _ in range(n):
    a.append(int(input()))

a.sort()
# print(a)
b = [0 for _ in range(n)]
b[n//2] = a[0]
left = 1
right = n-1
for i in range(n//2):
    if i%2==0:
        b[n//2-(i+1)] = a[right]
        right -= 1
        if n//2+(i+1)<n:
            b[n//2+(i+1)] = a[right]
            right -= 1
    else:
        b[n//2-(i+1)] = a[left]
        left += 1
        if n//2+(i+1)<n:
            b[n//2+(i+1)] = a[left]
            left += 1
ans1 = 0
for i in range(n-1):
    ans1 += abs(b[i]-b[i+1])




b = [0 for _ in range(n)]
b[n//2] = a[n-1]
left = 0
right = n-2
for i in range(n//2):
    if i%2==1:
        b[n//2-(i+1)] = a[right]
        right -= 1
        if n//2+(i+1)<n:
            b[n//2+(i+1)] = a[right]
            right -= 1
    else:
        b[n//2-(i+1)] = a[left]
        left += 1
        if n//2+(i+1)<n:
            b[n//2+(i+1)] = a[left]
            left += 1
ans2 = 0
for i in range(n-1):
    ans2 += abs(b[i]-b[i+1])

print(max(ans1,ans2))

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
a = [int(input()) for _ in range(n)]
a.sort()
que = deque(a)
right = que.pop()
left = que.popleft()
sums = right - left
while(bool(que)):
  a = que.pop()
  if not bool(que):
    sums += max(abs(right-a),abs(left-a))
    break
  b = que.popleft()
  sums += right + a - left -b
  right = a
  left = b

print(sums)

Submission status: Accepted

Solution code:
N = int(input())
A =[0]*N
for i in range(N):
    A[i] = int(input())
A.sort(reverse=True)
X=0
Y=0
if N % 2 == 0:
    for i in range(N//2-1):
        X = X + 2*A[i] -2*A[-i-1]
    X = X + A[N//2-1] -A[N//2]
    print(X)    

if N % 2 == 1:
        for i in range(N//2):
            X = X + 2 * A[i]
            Y = Y - 2 * A[-i-1]
        for i in range (N//2-1):
            X = X - 2 * A[-i-1]
            Y = Y + 2 * A[i]
        X = X - A[N//2] - A[N//2+1]
        Y = Y + A[N//2-1] + A[N//2]
        print(max(X,Y))

Submission status: Accepted

Solution code:
def run(N, A):
    A = sorted(A)
    ret = 0
    for i in range(N//2):
        ret += A[-(i+1)] - A[i]
        aa = A[-(i+1)] - A[i]
        if N - (i+1) != i + 1:
            ret += A[-(i+1)] - A[i+1]
            aa = A[-(i+1)] - A[i+1]
    i = N//2 - 1
    ret -= aa
    ret += A[i+1] - A[0]

    ret2 = 0
    for i in range(N//2):
        ret2 += A[-(i+1)] - A[i]
        aa = A[-(i+1)] - A[i]
        if N - (i+2) != i:
            ret2 += A[-(i+2)] - A[i]
            aa = A[-(i+2)] - A[i]
    i = N//2 - 1
    ret2 -= aa
    ret2 += A[-1] - A[-(i+2)]
    return max(ret, ret2)


def main():
    N = int(input())
    A = []
    for i in range(N):
        A.append(int(input()))
    print(run(N, A))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n=int(input())
l=[]
for i in range(n):
  l.append(int(input()))
l.sort()
if n%2==0:
  m=n//2
  sum1=0
  sum2=0
  for j in range(m):
    sum1 += l[j]
    sum2 += l[n-1-j]
  max=2*sum2-2*sum1-l[m]+l[m-1]
  print(max)
else:
  if n==3:
    max1=l[2]+l[1]-2*l[0]
    max2=2*l[2]-l[1]-l[0]
    if  (max1>max2):
      print(max1)
    else:
      print(max2)
  else:
    m=(n-1)//2
    sum1=0
    sum2=0
    for j in range(m+1):
      sum1 += l[j]
      sum2 += l[n-1-j]
    max1=2*sum2-l[m]-l[m+1]-2*sum1+2*l[m]
    max2=2*sum2-2*l[m]-2*sum1+l[m]+l[m-1]
    if  (max1>max2):
      print(max1)
    else:
      print(max2)

Submission status: Accepted

Solution code:
import numpy as np
N = int(input().strip('\n'))
lis = []
for i in range(N):
    lis.append(int(input().strip('\n')))
lis = np.sort(np.array(lis))
mx_n = lis[-1]
ms_n = lis[0]
lis = lis[1:-1]
point = mx_n-ms_n
while lis.shape[0]>=2:
    mx = lis[-1]
    ms = lis[0]
    point += (mx_n-ms+mx-ms_n)
    mx_n = mx
    ms_n = ms
    lis = lis[1:-1]
if lis.shape[0]==1:
    point += max(abs(mx_n-lis[0]),abs(ms_n-lis[0]))
print(point)

Submission status: Accepted

Solution code:
import collections

N = int(input())

A = [0] * N
for i in range(N):
    A[i] = int(input())


A = sorted(A)

if N % 2 == 1:
    d1 = A[0:N // 2 + 1]
    u1 = A[N // 2 + 1:N + 1]
else:
    d1 = A[0:N // 2]
    u1 = A[N // 2:N + 1]

d1 = collections.deque(d1)
u1 = collections.deque(u1)
d1.rotate(1)
u1.rotate(-1)

sum1 = 0
i = 0
while (True):
    # print("{},{},{}".format(i, len(d1), len(u1)))
    if i >= len(d1) or i >= len(u1):
        break
    sum1 += abs(u1[i] - d1[i])

    if i+1 >= len(d1) or i >= len(u1):
        break
    sum1 += abs(u1[i] - d1[i + 1])
    i += 1

sum2 = 0
i = 0
while (True):
    # print("{},{},{}".format(i, len(d1), len(u1)))
    if i >= len(d1) or i >= len(u1):
        break
    sum2 += abs(u1[i] - d1[i])

    if i >= len(d1) or i+1 >= len(u1):
        break
    sum2 += abs(u1[i+1] - d1[i])
    i += 1

###########################

if N % 2 == 1:
    d1 = A[0:N // 2]
    u1 = A[N // 2:N + 1]

d1 = collections.deque(d1)
u1 = collections.deque(u1)
d1.rotate(1)
u1.rotate(-1)

sum3 = 0
i = 0
while (True):
    # print("{},{},{}".format(i, len(d1), len(u1)))
    if i >= len(d1) or i >= len(u1):
        break
    sum3 += abs(u1[i] - d1[i])

    if i+1 >= len(d1) or i >= len(u1):
        break
    sum3 += abs(u1[i] - d1[i + 1])
    i += 1

sum4 = 0
i = 0
while (True):
    # print("{},{},{}".format(i, len(d1), len(u1)))
    if i >= len(d1) or i >= len(u1):
        break
    sum4 += abs(u1[i] - d1[i])

    if i >= len(d1) or i+1 >= len(u1):
        break
    sum4 += abs(u1[i+1] - d1[i])
    i += 1


print(max(sum1, sum2, sum3, sum4))

Submission status: Accepted

Solution code:
def cul(low, high):
    high = high[::-1]
    lists = []
    if len(low) > len(high):
        low.insert(0, low[-1])
        low = low[:-1]
        lists.append(low[0])
        for _l, _h in zip(low[1:], high):
            lists.append(_h)
            lists.append(_l)
    elif len(low) < len(high):
        high.insert(0, high[-1])
        high = high[:-1]
        lists.append(high[0])
        for _l, _h in zip(low, high[1:]):
            lists.append(_l)
            lists.append(_h)
    else:
        low.insert(0, low[-1])
        low = low[:-1]
        for _l, _h in zip(low, high):
            lists.append(_l)
            lists.append(_h)
    ans = 0
    for _p, _n in zip(lists, lists[1:]):
        ans += abs(_n - _p)
    return ans


n = int(input())
a = sorted([int(input()) for _ in range(n)])
if len(a) % 2 == 1:
    lower = a[:len(a) // 2 + 1]
    higher = a[len(a) // 2 + 1:]
    first = cul(lower, higher)
    lower = a[:len(a) // 2]
    higher = a[len(a) // 2:]
    second = cul(lower, higher)
    print(max(first, second))
else:
    lower = a[:len(a) // 2]
    higher = a[len(a) // 2:]
    print(cul(lower, higher))

Submission status: Accepted

Solution code:
# Align
""" Tenka1 Programmer Beginner Contest C """

test = False
A = []

N = int(input())
for _ in range(N):
    A.append(int(input()))


def answer(n, l):
    """中心が最小"""
    x = 0
    y = 0

    if n == 2:
        return abs(l[0] - l[1])

    if n%2 == 1: # nが奇数の時
        l.sort()
        for i in range(n//2):
            x += 2 * l[-(i+1)]
            x -= 2 * l[i]
        x -= l[n//2]
        x += l[n//2 -1]

        l.sort(reverse=True)
        for i in range(n//2):
            y += 2 * l[-(i+1)]
            y -= 2 * l[i]
        y -= l[n//2]
        y += l[n//2 -1]

        if test:
            print('x =', x)
            print('y =', y)
        return max(x, -y)

    # nが偶数の時
    l.sort()
    for i in range(n//2 -1):
        x += 2 * l[-(i+1)]
        x -= 2 * l[i]
    x += l[n//2]
    x -= l[n//2 -1]

    return x


def main():
    """main"""
    print(answer(N, A))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=input()
N=int(N)
L=[]

def diff(L):
    total=0
    for i in range(len(L)-1):
        total+=abs(L[i+1]-L[i])
    return total
for i in range(N):
    A=input()
    L.append(int(A))
L.sort()
if len(L)>3:
    length=len(L)
    SL=L[:int(length/2)]
    LL=L[int(length/2):]
    result=[]
    result.append(SL[-1])
    SL.pop(-1)
    last=LL[0]
    LL.pop(0)
    while True:
        try:
            result.append(LL[-1])
            LL.pop(-1)
            result.append(SL[0])
            SL.pop(0)
        except:
            break
    if abs(result[-1]-last)>=abs(result[0]-last): 
        result.append(last)
    else:
        result.insert(0,last)
    print(diff(result))
elif len(L)==3:
    all=[diff([L[0],L[1],L[2]]),diff([L[0],L[2],L[1]]),diff([L[1],L[0],L[2]]),diff([L[1],L[2],L[0]]),diff([L[2],L[0],L[1]]),diff([L[2],L[1],L[0]])]
    print(max(all))
elif len(L)==2:
    print(abs(L[0]-L[1]))

Submission status: Accepted

Solution code:
N = int(input())
A = [int(input()) for _ in range(N)]
B = sorted(A, reverse=False)
A.sort(reverse=True)

if N == 2:
    print(abs(A[0] - A[1]))
else:
    l_in = 0
    r_in = len(A) - 1
    ans_a = (A[l_in] - A[r_in]) + (A[l_in] - A[r_in - 1])
    hashi = [A[r_in], A[r_in-1]]
    l_in += 1
    r_in -= 2
    while l_in != r_in and N != 3:
        l_max = max(abs(A[l_in] - hashi[0]), abs(A[l_in] - hashi[1]))
        r_max = max(abs(A[r_in] - hashi[0]), abs(A[r_in] - hashi[1]))
        if l_max > r_max:
            if abs(A[l_in] - hashi[0]) > abs(A[l_in] - hashi[1]):
                ans_a += abs(A[l_in] - hashi[0])
                hashi[0] = A[l_in]
            else:
                ans_a += abs(A[l_in] - hashi[1])
                hashi[1] = A[l_in]
            l_in += 1
        else:
            if abs(A[r_in] - hashi[0]) > abs(A[r_in] - hashi[1]):
                ans_a += abs(A[r_in] - hashi[0])
                hashi[0] = A[r_in]
            else:
                ans_a += abs(A[r_in] - hashi[1])
                hashi[1] = A[r_in]
            r_in -= 1
    # last
    if l_in == r_in:
        if abs(A[l_in] - hashi[0]) > abs(A[l_in] - hashi[1]):
            ans_a += abs(A[l_in] - hashi[0])
            hashi[0] = A[l_in]
        else:
            ans_a += abs(A[l_in] - hashi[1])
            hashi[1] = A[l_in]

    l_in = 0
    r_in = len(B) - 1
    ans_b = abs(B[l_in] - B[r_in]) + abs(B[l_in] - B[r_in - 1])
    hashi = [B[r_in], B[r_in - 1]]
    l_in += 1
    r_in -= 2
    while l_in != r_in and N != 3:
        l_max = max(abs(B[l_in] - hashi[0]), abs(B[l_in] - hashi[1]))
        r_max = max(abs(B[r_in] - hashi[0]), abs(B[r_in] - hashi[1]))
        if l_max > r_max:
            if abs(B[l_in] - hashi[0]) > abs(B[l_in] - hashi[1]):
                ans_b += abs(B[l_in] - hashi[0])
                hashi[0] = B[l_in]
            else:
                ans_b += abs(B[l_in] - hashi[1])
                hashi[1] = B[l_in]
            l_in += 1
        else:
            if abs(B[r_in] - hashi[0]) > abs(B[r_in] - hashi[1]):
                ans_b += abs(B[r_in] - hashi[0])
                hashi[0] = B[r_in]
            else:
                ans_b += abs(B[r_in] - hashi[1])
                hashi[1] = B[r_in]
            r_in -= 1
    # last
    if l_in == r_in:
        if abs(B[l_in] - hashi[0]) > abs(B[l_in] - hashi[1]):
            ans_b += abs(B[l_in] - hashi[0])
            hashi[0] = B[l_in]
        else:
            ans_b += abs(B[l_in] - hashi[1])
            hashi[1] = B[l_in]

    print(max(ans_a, ans_b))

Submission status: Accepted

Solution code:
from collections import deque

N = int(input())
A = [int(input()) for _ in range(N)]

A.sort()
array = deque([A[0]])
a_len = 1
count = 0
idx = 0
result1 = 0

while a_len < N:
    if count % 2 == 0:
        array.appendleft(A[-idx-1])
        array.append(A[-idx-2])
    else:
        array.appendleft(A[idx+1])
        array.append(A[idx+2])
        idx += 2
    count += 1
    a_len += 2

for i in range(N-1):
    result1 += abs(array[i] - array[i+1])

array = deque([A[-1]])
a_len = 1
count = 0
idx = 0
result2 = 0

while a_len < N:
    if count % 2 != 0:
        array.appendleft(A[-idx])
        array.append(A[-idx-1])
    else:
        array.appendleft(A[idx])
        array.append(A[idx+1])
        idx += 2
    count += 1
    a_len += 2

for i in range(N-1):
    result2 += abs(array[i] - array[i+1])

print(max(result1, result2))

Submission status: Accepted

Solution code:
def tpbc_2018_c():
    n = int(input())
    a = [int(input()) for _ in range(n)]
    a.sort()
    low = a[:len(a) // 2]
    high = a[len(a) // 2:]
    if len(a) % 2 == 0:
        return 2 * (sum(high) - sum(low)) + max(low) - min(high)
    else:
        low2 = a[:len(a) // 2 + 1]
        high2 = a[len(a) // 2 + 1:]
        return max(2 * (sum(high) - sum(low)) - high[0]-high[1],2 * (sum(high2) - sum(low2))+low2[-2]+low2[-1])


print(tpbc_2018_c())

Submission status: Accepted

Solution code:
N = int(input())
a = [0]*N
result = []
for i in range(N):
 a[i] = int(input())
a = sorted(a)
if N%2 != 0:
 a_sub = sorted(a,key=lambda x: -x)
 a_0 =a[N//2]
 for j in range(N//2):
  if j %2 ==0:
   result.insert(0,a_sub[j])
   result.append(a[j])
  else:
   result.insert(0,a[j])
   result.append(a_sub[j])
 tmp1 = abs(result[0] - a_0)
 tmp2 = abs(result[N-2] -a_0)
 if tmp1 < tmp2:
  result.append(a_0)  
 else:
  result.insert(0,a_0)
else:
 a_sub = sorted(a,key=lambda x: -x)
 for j in range(N//2):
  if j %2 ==0:
   result.insert(0,a_sub[j])
   result.append(a[j])
  else:
   result.insert(0,a[j])
   result.append(a_sub[j])
result_sum = 0
for k in range(N-1):
 result_sum = result_sum + abs(result[k] - result[k+1])
print(result_sum)

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
nums =[]

for i in range(n):
  nums.append(int(input()))

nums.sort()
nums = deque(nums)
a = [nums.pop()]
a = deque(a)

while not len(nums) == 0:
  try:
    a.appendleft(nums.popleft())
    a.append(nums.popleft())
    a.appendleft(nums.pop())
    a.append(nums.pop())
  except IndexError:
    pass

tmp_1 = abs(a[-1] - a[-2])
tmp_2 = abs(a[-1] - a[0])

if tmp_1 < tmp_2:
  a.appendleft(a.pop())

sub = 0
for i in range(1, len(a)):
  sub += abs(a[i-1]-a[i])
print(sub)

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
nums = []
ans = deque()
for i in range(n):
    nums.append(int(input()))
if n == 2:
    print(abs(nums[0]-nums[1]))
elif n == 3:
    nums.sort
    print(max(abs(nums[0]-nums[1])+abs(nums[1]-nums[2]),abs(nums[0]-nums[2])+abs(nums[0]-nums[1]),abs(nums[2]-nums[1])+abs(nums[2]-nums[0])))
else:
    nums.sort()
    nums = deque(nums)
    a = nums.popleft()
    ans.append(a)
    b = nums.pop()
    ans.append(b)
    c = nums.popleft()
    ans.append(c)
    anser = abs(a-b) + abs(b-c)
    while len(nums) != 0:
        imin = nums[0]
        imax = nums[-1]
        amin = ans[0]
        amax = ans[-1]
        do = (abs(imin-amin),abs(imin-amax),abs(imax-amin),abs(imax-amax))
        domax = max(do)
        doindex = do.index(domax)
        if doindex == 0:
            nums.popleft()
            ans.appendleft(imin)
        elif doindex == 1:
            nums.popleft()
            ans.append(imin)
        elif doindex == 2:
            nums.pop()
            ans.appendleft(imax)
        else:
            nums.pop()
            ans.append(imax) 
        anser += domax
    print(anser)

Submission status: Accepted

Solution code:
import  math
def getN():
    return int(input())


def getNM():
    return map(int, input().split())


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

n = getN()
nums = []


for i in range(n):
  nums.append(getN())

if n == 2:
    print(abs(nums[0]-nums[1]))

if n > 2:
    half = int(math.floor(n/2))
    nums.sort()
    nums1 = nums[:half]
    nums2 = nums[half:]
    nums2[1], nums2[-1] = nums2[-1], nums2[1]

    tmp = nums2[0]
    diff = 0
    diff2 = 0
    for i in range(half):
        num = nums2[i]
        diff += abs(tmp-num)
        tmp = num

        num = nums1[i]
        diff += abs(tmp - num)
        tmp = num

    if n%2 == 1:
        diff += abs(tmp-nums2[-1])

    if n%2 == 1:
        nums1 = nums[:half+1]
        nums2 = nums[half+1:]
        nums1[0], nums1[-2] = nums1[-2], nums1[0]

        tmp = nums1[0]
        for i in range(half):
            num = nums1[i]
            diff2 += abs(tmp - num)
            tmp = num

            num = nums2[i]
            diff2 += abs(tmp - num)
            tmp = num

        diff2 += abs(tmp-nums1[-1])

    #print(nums1)
    #print(nums2)
    print(max(diff, diff2))
"""
3 4 5 9
1 1 3
"""

Submission status: Accepted

Solution code:
import numpy as np
N=int(input())
A=np.empty(N)
for i in range(N):
    A[i]=int(input())
m = np.median(A)
dA = np.abs(A-m)
sdA=np.sort(dA)
D = int(sdA[0:2].sum() + sdA[2:].sum()*2)
print(D)

Submission status: Accepted

Solution code:
n = int(input())
a = []
b = []
d = []
c = 0
for i in range(n):
 ak = int(input())
 a.append(ak)
a.sort()
for i in range((len(a)-1)//2):
 d.append(a[-i-1]-a[i])
for i in range(n-1):
 bk = a[i+1] -  a[i]
 b.append(bk)
e = len(b)
c = sum(d) * 2
if e % 2 == 1:
 c += b[e//2]
else:
 c -= min(b[e//2-1],b[e//2])
print(c)

Submission status: Accepted

Solution code:
N = int(input())
A = [0]*N
for i in range(N):
    A[i] = int(input())
A.sort()
if N%2 == 1:
    print(max(sum(A[N//2+1:])*2-sum(A[:N//2-1])*2-sum(A[N//2-1:N//2+1]),sum(A[N//2+2:])*2-sum(A[:N//2])*2+A[N//2]+A[N//2+1]))
else:
    print(sum(A[N//2+1:])*2+A[N//2]-sum(A[:N//2-1])*2-A[N//2-1])

Submission status: Accepted

Solution code:
n = int(input())
a = sorted(list(map(int, [input() for i in range(n)])), reverse=True)
if n % 2 == 0:
  print(2*sum(a[:int(n/2)])-2*sum(a[-int(n/2):])-a[int(n/2-1)]+a[int(n/2)])
else:
  x = 2*sum(a[:int((n-1)/2)])-2*sum(a[-int((n-1)/2):])-a[int((n-1)/2)]+a[int((n-1)/2+1)]
  y = 2*sum(a[:int((n-1)/2)])-2*sum(a[-int((n-1)/2):])+a[int((n-1)/2)]-a[int((n-1)/2-1)]
  if x > y:
    print(x)
  else:
    print(y)

Submission status: Accepted

Solution code:
import math

def gcd(a,b):
    """Compute the greatest common divisor of a and b"""
    while b > 0:
        a, b = b, a % b
    return a

def lcm(a, b):
    """Compute the lowest common multiple of a and b"""
    return a * b / gcd(a, b)


def best_alignment(lst, small):

	ans = 0

	p = []

	if(small):
		p.append(lst[-1])
		p.append(lst[-1])
		del lst[-1:]
	else:
		m = min(lst)
		p.append(lst[0])
		p.append(lst[0])
		lst.pop(0)


	while(len(lst)>0):

		if(small):
			ans = ans + abs(max(p)-lst[0])
			if(len(lst)==1):
				break

			ans = ans + abs(min(p)-lst[1])

			p = []
			p.append(lst.pop(0))
			p.append(lst.pop(0))
			small = False
			continue
		else:
			ans = ans + abs(min(p)-lst[-1])
			if(len(lst)==1):
				break

			ans = ans + abs(max(p)-lst[-2])

			p = []
			p.append(lst[-1])
			p.append(lst[-2])
			del lst[-2:]
			small = True
			continue

	return ans	




N = int(input().strip())
A = []
for i in range(N):
	A.append(int(input().strip()))

A.sort()
A_=A.copy()

print(max(best_alignment(A, True), best_alignment(A_, False)))

Submission status: Accepted

Solution code:
n = int(input())
listA=[]
index=0
while index < n:
    listA.append(int(input()))
    index+=1
listA.sort()


if len(listA)%2==0:
    sum = listA[len(listA)//2]-listA[len(listA)//2-1]
    index=0
    while index < len(listA):
        if index == len(listA)//2-1 or index == len(listA)//2:
            pass
        else:
            if index < len(listA)//2:
                sum-=2*listA[index]
            else:
                sum+=2*listA[index]
        index+=1
    print(sum)
else:
    sum=-1*(listA[len(listA)//2]+listA[len(listA)//2-1])
    index = 0
    while index < len(listA):
        if index == len(listA)//2-1 or index == len(listA)//2:
            pass
        else:
            if index < len(listA)//2:
                sum -= 2*listA[index]
            else:
                sum += 2*listA[index]
        index += 1
    sumB = listA[len(listA)//2]+listA[len(listA)//2+1]
    index2 = 0
    while index2 < len(listA):
        if index2 == len(listA)//2 or index2 == len(listA)//2+1:
            pass
        else:
            if index2 < len(listA)//2:
                sumB -= 2*listA[index2]
            else:
                sumB += 2*listA[index2]
        index2 += 1

    print(max(sum, sumB))