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: Time Limit Exceeded

Solution code:
from collections import deque
N = input()
A = []
for i in range(N):
	a = input()
	A.append(a)

A = sorted(A)
res = []
begin = 0
end = len(A) - 1
res = deque()
res.append(A[begin])
res.append(A[end])
begin += 1
end -= 1
for i in range(N - 2):
	l = [abs(res[0] - A[begin]), abs(res[0] - A[end]), abs(res[-1] - A[begin]), abs(res[-1] - A[end])]
	cand = l.index(max(l))
	if cand == 0:
		res.appendleft(A[begin])
		begin += 1
	elif cand == 1:
		res.appendleft(A[end])
		end -= 1
	elif cand == 2:
		res.append(A[begin])
		begin += 1
	elif cand == 3:
		res.append(A[end])
		end -= 1
sum_diff = 0
for i in range(N - 1):
	 sum_diff += abs(res[i] - res[i + 1])
print sum_diff

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import copy

N = int(raw_input().replace("\n", ""))

a_array = np.asarray([int(raw_input().replace("\n", "")) for i in xrange(N)])
len_array = a_array.shape[0]

sum_diffs = []
for elm_i, start_elm in enumerate(a_array):
    mask = np.ones(len_array, dtype=bool)
    target_elm = start_elm
    #mask[elm_i] = False

    sum_diff = 0
    #while True:
    for count in xrange(len_array - 1):
        #a_list.remove(target_elm)
        mask[elm_i] = False
        a_list = a_array[mask]
        #print(a_array, mask, a_list, count)
        #a_array = np.abs(np.asarray(a_list) - target_elm)
        tmp = np.abs(a_list - target_elm)
        #target_elm_index = np.argmax(a_array)
        target_elm_index = np.argmax(tmp)
        target_elm = a_list[target_elm_index]
        sum_diff += tmp[target_elm_index]
        #print("sum_diff:", sum_diff)
        
        count_ = -1
        for mask_i, elm in enumerate(mask):
            if elm:
                count_ += 1
                if count_ == target_elm_index:
                    elm_i = mask_i
                    break
        #print target_elm_index, elm_i
    
    sum_diffs.append(sum_diff)

#print sum_diffs
print max(sum_diffs)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
def findbest(liste, i):
	lister = liste[:]
	lister.remove(i)
	returnlister = [i]
	t = len(lister)
	output = 0
	while(t >= 2):
		if abs(i - lister[-1]) >= abs(i - lister[0]):
			returnlister.append(lister.pop(-1))
		else:
			returnlister.append(lister.pop(0))
		i = returnlister[-1]
		t -= 1
	returnlister.extend(lister)
	
	for i in range(len(returnlister) - 1):
		output += abs(returnlister[i] - returnlister[i + 1])
	return output
 
a = int(input())
numlist = []
for i in range(a):
	numlist.append(int(input()))
 
numlist = sorted(numlist)
possible = list(set(numlist))
maxer = 0
if len(possible) <= 3:
	for i in possible:
		maxer = max(findbest(numlist, i), maxer)
else:
	for i in possible[len(possible)//2 - 1: len(possible)//2 + 2]:
		maxer = max(findbest(numlist, i), maxer)
		
print (maxer)

Submission status: Time Limit Exceeded

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

def s(a):
    ass = 0
    if len(a)== 1:
        return 0
    for i in range(1,n):
        ass += abs(a[i]-a[i-1])
    return ass   
    
ans = [a[0]]
w = 1
while w < n:
    if w % 4 == 1:
        ans.insert(0,a[n-1-(w//4)*2])
    elif w % 4 == 2:
        ans.append(a[n-2-(w//4)*2])
    elif w % 4 == 3:
        ans.insert(0,a[1+(w//4)*2])
    else:
        ans.append(a[(w//4)*2])
    w += 1
jkl = [s(ans)]

ans = [a[n-1]]
w = 1
while w < n:
    if w % 4 == 1:
        ans.insert(0,a[0+(w//4)*2])
    elif w % 4 == 2:
        ans.append(a[1+(w//4)*2])
    elif w % 4 == 3:
        ans.insert(0,a[n-2-(w//4)*2])
    else:
        ans.append(a[n-1-(w//4)*2])
    w += 1
jkl.append(s(ans))

print(max(jkl))

Submission status: Time Limit Exceeded

Solution code:
from random import shuffle

n = int(input())
a = sorted([int(input()) for x in range(n)])
ans = 0
for x in range(100):
    shuffle(a)
    temp = 0
    for i in range(n - 1):
        temp += abs(a[i] - a[i + 1])
    if ans < temp:
        ans = temp
print(ans)

Submission status: Time Limit Exceeded

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


def distance(p, Array):
    
    m = 0
    index = 0
    for i in range(len(Array)):
        if m < abs(p - Array[i]):
            m = abs(p - Array[i])
            index = i
    return index


A.sort()
S = 0
for f in range(N):
    B = copy.deepcopy(A)
    bi = B.pop(f)
    s = 0 
    #print(bi, "----")
    while B:
        j = distance(bi, B)

        # b[j] が bi から一番遠い
        bj = B.pop(j)
        s += abs(bi - bj)
       # print(s, bi, bj)

        bi = bj
        
    
    if S < s:
        S = s

print(S)

Submission status: Time Limit Exceeded

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()

b = [a[0]]
a=a[1:]

f=True
while len(a)>0:
  ln = abs(b[0]-a[0])
  lx = abs(b[0]-a[len(a)-1])
  rn = abs(b[len(b)-1]-a[0])
  rx = abs(b[len(b)-1]-a[len(a)-1])

  x = max(ln, max(lx, max(rn, rx)))
  
  if x == ln:
    b.insert(0,a[0])
    a=a[1:]
  elif x == lx:
    b.insert(0,a.pop())
  elif x == rn:
    b.append(a[0])
    a=a[1:]
  else:
    b.append(a.pop())

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

Submission status: Time Limit Exceeded

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

s=[]
k=len(num)
while 1:
    if k>1:
        s.append(num.pop(0))
        s.insert(0,num.pop(-1))
        s=s[::-1]
        k-=2
    elif k==1:
        if abs(s[0]-num[0])<abs(s[-1]-num[0]):
            s.append(num[0])
        else:
            s.insert(0,num[0])
        break
    else:
        break

S=0
for i in range(len(s)-1):
    S+=abs(s[i]-s[i+1])
print(S)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

A = [0 for _ in range(n)]
for i in range(n):
    a = int(input())
    for k in range(i):
        if a <= A[k]:
            # print(A[k + 1: i + 1], A[k:i])
            A[k + 1: i + 1] = A[k: i]
            A[k] = a
            break
    else:
        A[i] = a
    # print(A)
# A.sort()
# print(A)

ans = 0
end = [A[0], A[-1]]
ans += abs(A[-1] - A[0])
A = A[1:-1]
while len(A) != 0:
    # print(ans, A, end)
    sl = [A[0], A[-1]]

    tmp_l = []
    tmp_l.append(abs(end[0] - sl[0]))
    tmp_l.append(abs(end[1] - sl[0]))
    tmp_l.append(abs(end[0] - sl[1]))
    tmp_l.append(abs(end[1] - sl[1]))

    tmp = max(tmp_l)
    index = tmp_l.index(tmp)
    ans += tmp

    # print(index, tmp_l[index])
    if index % 2 == 0:
        end[0] = sl[index == 2]

    else:
        end[1] = sl[index == 3]

    if index < 2:
        A = A[1:]
    else:
        A = A[:-1]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
num=[]
for i in range(N):
  num.append(int(input()))
num.sort()
jun=[]
sig=[i for i in range(1,N+1)]
if N%2!=0: #kisu
  manaka=int(N/2)
  if abs(num[manaka]-num[0])<abs(num[manaka]-num[N-1]):
    jun.append(manaka)
    for i in range(int((N-1)/2)):
      jun.append(max(sig)-1)
      sig.remove(max(sig))
      jun.append(min(sig)-1)
      sig.remove(min(sig))
  else:
    jun.append(manaka)
    for i in range(int((N-1)/2)):
      jun.append(min(sig)-1)
      sig.remove(min(sig))
      jun.append(max(sig)-1)
      sig.remove(max(sig))
else:
  manaka=int(N/2)
  jun.append(manaka)
  for i in range(manaka-1):
    jun.append(min(sig)-1)
    sig.remove(min(sig))
    jun.append(max(sig)-1)
    sig.remove(max(sig))
  jun.append(sig[0]-1)
sum=0
for i in range(N-1):
  sum+=abs(num[jun[i]]-num[jun[i+1]])
print(sum)

Submission status: Time Limit Exceeded

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

p = a.count(a[0])
q = a.count(a[n-1])

def s(a):
    ass = 0
    if len(a)== 1:
        return 0
    for i in range(1,n):
        ass += abs(a[i]-a[i-1])
    return ass   
    
if p ==1:
    ans = [a[0]]
    w = 1
    while w < n:
        if w % 4 == 1:
            ans.insert(0,a[n-1-(w//4)*2])
        elif w % 4 == 2:
            ans.append(a[n-2-(w//4)*2])
        elif w % 4 == 3:
            ans.insert(0,a[1+(w//4)*2])
        else:
            ans.append(a[(w//4)*2])
        w += 1
    print(s(ans))
elif q == 1:
    ans = [a[n-1]]
    w = 1
    while w < n:
        if w % 4 == 1:
            ans.insert(0,a[0+(w//4)*2])
        elif w % 4 == 2:
            ans.append(a[1+(w//4)*2])
        elif w % 4 == 3:
            ans.insert(0,a[n-2-(w//4)*2])
        else:
            ans.append(a[n-1-(w//4)*2])
        w += 1
    print(s(ans))
else:
    jkl = a[n-1]-a[0]
    if p > q:
        for i in range(q):
            del a[0]
            del a[len(a)-1]
        n = n-2*q
        ans = [a[0]]
        w = 1
        while w < n:
            if w % 4 == 1:
                ans.insert(0,a[n-1-(w//4)*2])
            elif w % 4 == 2:
                ans.append(a[n-2-(w//4)*2])
            elif w % 4 == 3:
                ans.insert(0,a[1+(w//4)*2])
            else:
                ans.append(a[(w//4)*2])
            w += 1
        print(s(ans)+jkl*2*q)
    elif q > p:
        for i in range(p):
            del a[0]
            del a[len(a)-1]
        n = n-2*p
        ans = [a[n-1]]
        w = 1
        while w < n:
            if w % 4 == 1:
                ans.insert(0,a[0+(w//4)*2])
            elif w % 4 == 2:
                ans.append(a[1+(w//4)*2])
            elif w % 4 == 3:
                ans.insert(0,a[n-2-(w//4)*2])
            else:
                ans.append(a[n-1-(w//4)*2])
            w += 1
        print(s(ans)+jkl*2*p)
    else:
        ans = [a[0]]
        w = 1
        while w < n:
            if w % 4 == 1:
                ans.insert(0,a[n-1-(w//4)*2])
            elif w % 4 == 2:
                ans.append(a[n-2-(w//4)*2])
            elif w % 4 == 3:
                ans.insert(0,a[1+(w//4)*2])
            else:
                ans.append(a[(w//4)*2])
            w += 1
        print(s(ans))

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

perm = itertools.permutations(A, len(A))
ans = []

for p in perm:
    total = 0
    for i in range(len(p)-1):
        total += abs(p[i] - p[i+1])
    ans.append(total)

print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

num = []
for i in range(N):
  num.append(int(input()))
  
ans = [min(num)]
num.remove(min(num))

for i in range(len(num)-1):
  if i % 4 == 0:
    m = max(num)
    ans.append(m)
    num.remove(m)
  elif i % 4 == 1:
    m = max(num)
    ans = [m] + ans
    num.remove(m)
  elif i % 4 == 2:
    m = min(num)
    ans.append(m)
    num.remove(m)
  else:
    m = min(num)
    ans = [m] + ans
    num.remove(m)

answer = max(abs(num[0]-ans[0]), abs(num[0]-ans[-1]))
for i in range(len(ans)-1):
  answer += abs(ans[i] - ans[i+1])
  
print(answer)

Submission status: Time Limit Exceeded

Solution code:
def solve(pos):
    start = pos
    ans = 0
    a = 0
    b = N - 1
    for i in range(N-1):
        if a==start:
            a += 1
        elif b==start:
            b -= 1
        if abs(A[a]-A[pos])>=abs(A[b]-A[pos]):
            ans += abs(A[a]-A[pos])
            pos = a
            a += 1
        else:
            ans += abs(A[b]-A[pos])
            pos = b
            b -= 1
        #print(ans, a, b)
    #print(ans)
    return ans

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

ans = 0
for pos in range(N):
    tmp = solve(pos)
    ans = max(ans, tmp)
print(ans)

Submission status: Time Limit Exceeded

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

A.sort()

ans = []
for i in range(N):
    if len(ans) == 0:
        ans.append(A.pop(0))
        continue

    (Ai, ai) = (0, 0)
    if abs(A[0]-ans[-1]) > abs(A[Ai]-ans[ai]):
        (Ai, ai) = (0, -1)
    if abs(A[-1]-ans[0]) > abs(A[Ai]-ans[ai]):
        (Ai, ai) = (-1, 0)
    if abs(A[-1]-ans[-1]) > abs(A[Ai]-ans[ai]):
        (Ai, ai) = (-1, -1)

    if ai == -1:
        ans.append(A.pop(Ai))
    else:
        ans.insert(0, A.pop(Ai))

anssum = 0
for i in range(len(ans)-1):
    anssum += abs(ans[i]-ans[i+1])

#print('ans', ans)
print(anssum)

Submission status: Time Limit Exceeded

Solution code:
import itertools

N = int(input())

x = []
for i in range(N):
    x1 = int(input())
    x.append(x1)

L = list(itertools.permutations(x))

num = 0
sub = []

for j in range(len(L)):
    list = L[j]
    sub.clear()
    for i in range(N-1):
        sub.append(abs(list[i+1]-list[i]))
    if num < sum(sub):
        num = sum(sub)

#sub = x[1:]-x[:-1]
print(num)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque
N = input()
A = []
for i in range(N):
	a = input()
	A.append(a)

A = sorted(A)
res = []
begin = 0
end = len(A) - 1
res = deque()
res.append(A[begin])
res.append(A[end])
begin+= 1
end -= 1
for i in range(N - 2):
	cand = np.argmax([abs(res[0] - A[begin]), abs(res[0] - A[end]), abs(res[-1] - A[begin]), abs(res[-1] - A[end])])
	if cand == 0:
		res.appendleft(A[begin])
		begin += 1
	elif cand == 1:
		res.appendleft(A[end])
		end -= 1
	elif cand == 2:
		res.append(A[begin])
		begin += 1
	elif cand == 3:
		res.append(A[end])
		end -= 1
sum_diff = 0
for i in range(N - 1):
	 sum_diff += abs(res[i] - res[i + 1])
print sum_diff

Submission status: Time Limit Exceeded

Solution code:
def findbest(liste, i):
	lister = liste.copy()
	lister.remove(i)
	returnlister = [i]
	t = len(lister)
	while(t >= 2):
		if abs(i - lister[-1]) >= abs(i - lister[0]):
			returnlister.append(lister.pop(-1))
		else:
			returnlister.append(lister.pop(0))
		i = returnlister[-1]
		t -= 1
	returnlister.extend(lister)
	output = 0
	for j in range(len(returnlister) - 1):
		output += abs(returnlister[j] - returnlister[j + 1])
	
	return output
 
a = int(input())
numlist = []
for i in range(a):
	numlist.append(int(input()))
 
numlist = sorted(numlist)
possible = list(set(numlist))
maxer = 0
if len(possible) <= 100:
	for i in possible:
		maxer = max(findbest(numlist, i), maxer)
else:
	for i in possible[len(possible)//2 - 1: len(possible)//2 + 2]:
		maxer = max(findbest(numlist, i), maxer)
		
print (maxer)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n = int(input())

list = [];

max_num = 0;
def sum_diff(l):
    #print(l)
    before = l[0]
    diff_num=0
    for index,n in enumerate(l):
        if(index != 0):
            diff = abs(n-before)
            before = n;
            diff_num += diff
    return diff_num

for i in range(n):
    num = int(input())
    list.append(num)

for v in itertools.permutations(list, n):
    each_diff_num = sum_diff(v)
    max_num = max(max_num, each_diff_num)
   # print(each_diff_num)

print(max_num)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import math

n = int(input())
a_list = list(map(int, [input() for _ in range(n)]))
len_alist = len(a_list)

p = permutations(a_list, len_alist)
max_p_diff = 0
for p_val in p:
    tmp_diff_sum = sum([abs(p_val[i+1] - p_val[i]) for i in range(len_alist - 1)])
    max_p_diff = max(max_p_diff, tmp_diff_sum)

print(max_p_diff)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

num = []
for i in range(N):
  num.append(int(input()))
  
num = sorted(num)
ans = [num[0]]
num.pop(0)

for i in range(len(num)-1):
  if i % 4 == 0:
    ans.append(num[-1])
    num.pop(-1)
  elif i % 4 == 1:
    ans = [num[-1]] + ans
    num.pop(-1)
  elif i % 4 == 2:
    ans.append(num[0])
    num.pop(0)
  else:
    ans = [num[0]] + ans
    num.pop(0)

answer = max(abs(num[0]-ans[0]), abs(num[0]-ans[-1]))
for i in range(len(ans)-1):
  answer += abs(ans[i] - ans[i+1])
  
print(answer)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n= int(input())
l = []
for i in range(n):
    l.append(int(input()))

m = 0
for i in itertools.permutations(l):
    p = 0
    for j in range(n-1):
        p += abs(i[j]-i[j+1])
    if p > m:
        m = p
print(m)

Submission status: Time Limit Exceeded

Solution code:
def findbest(liste, i):
	lister = liste.copy()
	lister.remove(i)
	returnlister = [i]
	while(len(lister) >= 2):
		if abs(i - lister[-1]) >= abs(i - lister[0]):
			returnlister.append(lister.pop(-1))
		else:
			returnlister.append(lister.pop(0))
		i = returnlister[-1]
	returnlister.extend(lister)
	output = 0
	for j in range(len(returnlister) - 1):
		output += abs(returnlister[j] - returnlister[j + 1])
	
	return output
 
a = int(input())
numlist = []
for i in range(a):
	numlist.append(int(input()))
 
numlist = sorted(numlist)
possible = list(set(numlist))
maxer = 0
if len(possible) <= 100:
	for i in possible:
		maxer = max(findbest(numlist, i), maxer)
else:
	for i in possible[len(possible)//2 - 1: len(possible)//2 + 2]:
		maxer = max(findbest(numlist, i), maxer)
		
print (maxer)

Submission status: Time Limit Exceeded

Solution code:
def findbest(liste, i):
	lister = liste.copy()
	lister.remove(i)
	returnlister = [i]
	while(len(lister) >= 2):
		if abs(i - lister[-1]) >= abs(i - lister[0]):
			returnlister.append(lister.pop(-1))
		else:
			returnlister.append(lister.pop(0))
		i = returnlister[-1]
	returnlister.extend(lister)
	output = 0
	for j in range(len(returnlister) - 1):
		output += abs(returnlister[j] - returnlister[j + 1])
	
	return output
 
a = int(input())
numlist = []
for i in range(a):
	numlist.append(int(input()))
 
numlist = sorted(numlist)
possible = list(set(numlist))
maxer = 0
if len(possible) <= 100:
	for i in possible:
		maxer = max(findbest(numlist, i), maxer)
else:
	for i in possible[len(possible)//2 - 2: len(possible)//2 + 2]:
		maxer = max(findbest(numlist, i), maxer)
		
print (maxer)

Submission status: Time Limit Exceeded

Solution code:
def findbest(liste, i):
	lister = liste.copy()
	lister.remove(i)
	returnlister = [i]
	while(len(lister) >= 2):
		if abs(i - lister[-1]) >= abs(i - lister[0]):
			returnlister.append(lister.pop(-1))
		else:
			returnlister.append(lister.pop(0))
		i = returnlister[-1]
	returnlister.extend(lister)
	output = 0
	for j in range(len(returnlister) - 1):
		output += abs(returnlister[j] - returnlister[j + 1])
	
	return output
 
a = int(input())
numlist = []
for i in range(a):
	numlist.append(int(input()))
 
numlist = sorted(numlist)
possible = list(set(numlist))
maxer = 0
if len(possible) <= 5:
	for i in possible:
		maxer = max(findbest(numlist, i), maxer)
else:
	for i in possible[len(possible)//2 - 10: len(possible)//2 + 10]:
		maxer = max(findbest(numlist, i), maxer)
		
print (maxer)

Submission status: Time Limit Exceeded

Solution code:
# encoding: utf-8
import math

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

A_up = sorted(A)
A_down = list(A_up[::-1])

rslt = []
idx_up = 0
idx_down = 0
for i in range(N):
    if i % 4 == 0:
        rslt = [A_up[idx_up]] + rslt
        idx_up += 1
    elif i % 4 == 1:
        rslt = rslt + [A_down[idx_down]]
        idx_down += 1
    elif i % 4 == 2:
        rslt = rslt + [A_up[idx_up]]
        idx_up += 1
    else:
        rslt = [A_down[idx_down]] + rslt
        idx_down += 1

# exception (N == 3, may be related with perfect graph ?)
if N == 3:
    if A_up[1] - A_up[0] > A_up[2] - A_up[1]:
        rslt = [A_up[1], A_up[0], A_up[2]]
    else:
        rslt = [A_up[1], A_up[2], A_up[0]]
        
ans = 0
prev = rslt[0]
for val in rslt[1:]:
    ans += (val - prev) if (val - prev) > 0 else (prev - val)
    prev = val

# print(rslt)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import itertools
N = int(input())
A = np.array([int(input()) for _ in range(N)])
c = np.diff(A)
result = []
B = list(itertools.permutations(A))
for c in B:
    c = abs(np.diff(np.array(c)))
    result.append(sum(c))

print(max(result))

Submission status: Time Limit Exceeded

Solution code:
import itertools
N = int(input())
A_list = []

for i in range(N):
    A_list.append(int(input()) )
A_list = tuple(A_list)
# print(A_list)

def calculate_x(list):
    len_list = len(list)
    sum = 0
    for i in range(len_list-1):
        sum = sum + abs(list[i]-list[i+1])
    return sum

A_list2 = list(itertools.permutations(A_list)) #all pattern
# print(A_list2)
max = 0
for i in range(len(A_list2)):
    # print(list(A_list2[i]))
    tmp = calculate_x(list(A_list2[i]))
    # print(tmp)
    if tmp > max:
        max = tmp
print(max)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import copy

N = int(raw_input().replace("\n", ""))

a_list = []

for i in xrange(N):
    a = int(raw_input().replace("\n", ""))
    a_list.append(a)

input_list = a_list

a_array = np.asarray(a_list)
sum_diffs = []
for start_elm in input_list:
    a_list = copy.deepcopy(input_list)
    target_elm = start_elm
    
    sum_diff = 0
    while len(a_list) >= 1:
        a_list.remove(target_elm)
        if len(a_list) >= 1:
            a_array = np.abs(np.asarray(a_list) - target_elm)
            target_elm_index = np.argmax(a_array)
            target_elm = a_list[target_elm_index]
            sum_diff += a_array[target_elm_index]
        else:
            #sum_diff += np.abs(a_list[0] - target_elm)
            break
    
    sum_diffs.append(sum_diff)

print max(sum_diffs)

Submission status: Time Limit Exceeded

Solution code:
n,*a=map(int,open(0).read().split())
b=sorted(a)
c=b[::-1]
l=[b[0]]
r=[c[0]]
b=b[1:]
c=c[1:]
for i in range(n-1):
    if i%2==1:
        if i//2%2:
            l=l+[b[0]]
            del b[0]
            r=[c[0]]+r
            del c[0]
        else:
            l=[b[len(b)-1]]+l
            del b[len(b)-1]
            r=[c[len(c)-1]]+r
            del c[len(c)-1]
    else:
        if i//2%2:
            l=[b[0]]+l
            del b[0]
            r=r+[c[0]]
            del c[0]
        else:
            l=l+[b[len(b)-1]]
            del b[len(b)-1]
            r=r+[c[len(c)-1]]
            del c[len(c)-1]
x=y=0
for i in range(1,n):
    x+=abs(l[i]-l[i-1])
    y+=abs(r[i]-r[i-1])
print(max(x,y))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

A = []
for _ in range(n):
    A.append(int(input()))
A.sort()

ans = 0
end = [A[0], A[-1]]
ans += abs(A[-1] - A[0])
A = A[1:-1]
while len(A) != 0:
    # print(ans, A, end)
    sl = [A[0], A[-1]]

    tmp_l = []
    tmp_l.append(abs(end[0] - sl[0]))
    tmp_l.append(abs(end[1] - sl[0]))
    tmp_l.append(abs(end[0] - sl[1]))
    tmp_l.append(abs(end[1] - sl[1]))

    tmp = max(tmp_l)
    index = tmp_l.index(tmp)
    ans += tmp

    # print(index, tmp_l[index])
    if index % 2 == 0:
        end[0] = sl[index == 2]

    else:
        end[1] = sl[index == 3]

    if index < 2:
        A = A[1:]
    else:
        A = A[:-1]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n = int(input())
inputs = []
max_sa = 0
temp_sa = 0

for var in range(0,n):
    a = int(input())
    inputs.append(a)

permutations_list = list(itertools.permutations(inputs))

for ls in permutations_list:
    for i in range(len(ls)):
        if(i==0 or i==len(ls)):
            continue
        temp_sa += abs(ls[i-1]-ls[i])
    if(max_sa < temp_sa):
        max_sa = temp_sa
    temp_sa = 0

print(max_sa)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import math

def main():
    N = int(input())
    A = [int(input()) for j in range(N)]
    max = 0
    for Ai in list(itertools.permutations(A)):
        if calc(Ai) > max:
            max = calc(Ai)
    print(int(max))


def calc(Ai):
    result = 0
    for i in range(len(Ai)-1):
        result += math.fabs(Ai[i] - Ai[i+1])
    return result


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import itertools

n = int(input())


lis = []
for i in range(n):
    lis.append(int(input()))

lis_p = list(itertools.permutations(lis))

max_l = 0
for l in lis_p:
    tmp_l = 0
    for i in range(len(l) - 1):
        tmp_l += abs(l[i] - l[i+1])
    if tmp_l > max_l:
        max_l = tmp_l
        #print(l)

print(max_l)

Submission status: Accepted

Solution code:
n = int(input())
alst = [int(input()) for _ in range(n)]
alst.sort()
if n % 2 == 0:
    mid = n // 2
    ans = sum(alst[mid + 1:]) * 2 + alst[mid] - sum(alst[:mid - 1]) * 2 - alst[mid - 1]
else:
    mid = n // 2
    ans1 = sum(alst[mid + 1:]) * 2 - sum(alst[:mid - 1]) * 2 - alst[mid - 1] - alst[mid]
    ans2 = sum(alst[mid + 2:]) * 2 - sum(alst[:mid]) * 2 + alst[mid + 1] + alst[mid]
    ans = max(ans1, ans2)
    
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = sorted(int(input()) for TN in range(0,N))
if N%2==0:
    S = A[:(N//2)]
    B = A[(N//2):]
    SS = -2*sum(S)+S[-1]
    BS = 2*sum(B)-B[0]
    PT = SS+BS
    print(PT)
else:
    S = A[:(N//2)]
    B = A[(N//2):]
    SS1 = -2*sum(S)
    BS1 = 2*sum(B)-B[0]-B[1]
    PT1 = SS1+BS1
    
    SS2 = -2*sum(S)+S[-1]
    BS2 = 2*sum(B)-3*B[0]
    PT2 = SS2+BS2
    print(max(PT1,PT2))

Submission status: Accepted

Solution code:
import sys
from itertools import permutations

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def main():
    N, *A = map(int, read().split())
    A.sort()

    vec1 = [0] * N
    vec2 = [0] * N
    for i in range(N - 1):
        if i % 2 == 0:
            vec1[i] += 1
            vec1[i + 1] -= 1
            vec2[i] -= 1
            vec2[i + 1] += 1
        else:
            vec1[i] -= 1
            vec1[i + 1] += 1
            vec2[i] += 1
            vec2[i + 1] -= 1

    vec1.sort()
    vec2.sort()

    ans1 = ans2 = 0
    for a, v1, v2 in zip(A, vec1, vec2):
        ans1 += a * v1
        ans2 += a * v2

    print(max(ans1, ans2))
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque

input = sys.stdin.readline

def main():
    N = int(input())
    A = []
    for _ in range(N):
        A.append(int(input()))
    A.sort()
    if N%2 == 0:
        Bp = A[N//2:]
        Bm = A[:N//2]
        ans = 2*sum(Bp) - min(Bp) - 2*sum(Bm) + max(Bm)
    else:
        Bp = A[N//2+1:]
        Bm = A[:N//2+1]
        cnt = 2*sum(Bp) - 2*sum(Bm) + sum(Bm[-2:])

        Cp = A[N//2:]
        Cm = A[:N//2]
        ans = max(cnt, 2*sum(Cp) - sum(Cp[:2]) - 2*sum(Cm))

    print(ans)
        
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
D = []
for _ in range(n):
  D.append(int(input()))
D.sort()
A = deque(D)
B = deque()
B.append(A.popleft())

maxflag = 0
while True:
  if len(A) == 0:
    break
  if len(A) == 1:
    a = A.pop()
    B.appendleft(a)
    break
  if maxflag % 2 == 0:
    a = A.pop()
    b = A.pop()
  else:
    a = A.popleft()
    b = A.popleft()
  B.appendleft(a)
  B.append(b)
  maxflag += 1
ans = 0
for i in range(len(B)-1):
  ans += abs(B[i] - B [i+1])

A = deque(D)
B = deque()
B.append(A.pop())

maxflag = 1
while True:
  if len(A) == 0:
    break
  if len(A) == 1:
    a = A.pop()
    B.appendleft(a)
    break
  if maxflag % 2 == 0:
    a = A.pop()
    b = A.pop()
  else:
    a = A.popleft()
    b = A.popleft()
  B.appendleft(a)
  B.append(b)
  maxflag += 1
ans2 = 0
for i in range(len(B)-1):
  ans2 += abs(B[i] - B [i+1])
print(max(ans, ans2))

Submission status: Accepted

Solution code:

def resolve():
    # 隣り合う要素の差を大きくするには、大きい数と小さい数が交互に現れればよい。
    # 数列をsortして両端から交互に要素を取り、並べていく
    # 並べ方のパターン 小大小大小大を例に
    # |a1 -a2| + |a2 - a3| + |a3-an-1| + |an-1 - an|
    # 式を見ると両端は1回、その他は2回計算される

    def f(arr):
        res = 0
        for i in range(N - 1):
            res += abs(arr[i + 1] - arr[i])
        return res

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

    # Nが偶数なら、大小…大小
    # Nが奇数なら、大小…大小大 or 小大…小大小の二択の良い方

    mid = N // 2
    ans = 0
    if N % 2 == 0:
        low, high = A[:mid], A[mid:]
        B = []
        for i in range(mid):
            B.append(high[i])
            B.append(low[i])
        ans = f(B)

    else:
        res1 = 0
        low, high = A[:mid], A[mid + 1:]
        B = []
        for i in range(mid):
            B.append(high[i])
            B.append(low[i])
        # 後方に追加
        B.append(A[mid])
        res1 = f(B)

        # 先頭に追加
        B = [A[mid]] + B[:-1]

        ans = max(res1, f(B))

    print(ans)


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:

def resolve():
    # 隣り合う要素の差を大きくするには、大きい数と小さい数が交互に現れればよい。
    # 数列をsortして両端から交互に要素を取り、並べていく
    # 並べ方のパターン
    # 大きい方から並べるか小さい方から並べるか
    # 最後に並べる数字を左端におくか右端におくか

    # 全パターン試す

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

    # 左から、大小大小大小に並べる(右に要素を付け足す)
    # 最後に余った要素をどっちの両端に追加するか試す
    res1 = 0
    left = 0
    right = N - 1
    i = 0
    while (right - left) > 1:
        res1 += abs(A[right] - A[left])
        if i % 2 == 0:
            right -= 1
        else:
            left += 1
        i += 1
    if N % 2 == 1:
        # res1 = max(左端、右端)
        res1 += max(abs(A[N - 1] - A[right]), abs(A[left] - A[right]))
    else:
        res1 += max(abs(A[N - 1] - A[left]), abs(A[right] - A[left]))

    # 右から、小大小大小に並べる(左に要素を付け足す)
    # 最後に余った要素をどっちの両端に追加するか試す
    res2 = 0
    left = 0
    right = N - 1
    i = 0
    while (right - left) > 1:
        res2 += abs(A[right] - A[left])
        if i % 2 == 0:
            left += 1
        else:
            right -= 1
        i += 1
    if N % 2 == 1:
        # res2 = max(右端,左端)
        res2 += max(abs(A[0] - A[left]), abs(A[left] - A[right]))
    else:
        res2 += max(abs(A[0] - A[right]), abs(A[right] - A[left]))

    ans = max(res1, res2)
    print(ans)


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
N = int(input())
A = [int(input()) for _ in range(N)]
A.sort()
ans = 0
left, right = 1, 0
el, er = A[0], A[0] 
while left + right < N:
    a = abs(A[left]-el)
    b = abs(A[left]-er)
    c = abs(A[-right-1]-el)
    d = abs(A[-right-1]-er)
    m = max(a, b, c, d)
    if m == a:
        ans += a
        el = A[left]
        left += 1
    elif m == b:
        ans += b
        er = A[left]
        left += 1
    elif m == c:
        ans += c
        el = A[-right-1]
        right += 1
    else:
        ans += d
        er = A[-right-1]
        right += 1

print(ans)