Problem:


Score : 300 points

Problem Statement

There is a circular pond with a perimeter of K meters, and N houses around them.

The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.

When traveling between these houses, you can only go around the pond.

Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Constraints

2 \leq K \leq 10^6

2 \leq N \leq 2 \times 10^5

0 \leq A_1 < ... < A_N < K

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K N
A_1 A_2 ... A_N

Output

Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Sample Input 1

20 3
5 10 15

Sample Output 1

10

If you start at the 1-st house and go to the 2-nd and 3-rd houses in this order, the total distance traveled will be 10.

Sample Input 2

20 3
0 5 15

Sample Output 2

10

If you start at the 2-nd house and go to the 1-st and 3-rd houses in this order, the total distance traveled will be 10.



Sample input:
20 3
5 10 15


Sample output:
10

Submission status: Time Limit Exceeded

Solution code:
K, N = tuple(int(v) for v in input().split())

A_list = tuple(int(a) for a in input().split())

# 各点の距離
x_iter = iter(A_list)
y_iter = iter(A_list)
next(y_iter)

d_list = [y - x for x, y in zip(x_iter, y_iter)]
d_list.append(K - A_list[-1] + A_list[0])
d_list += d_list

l = len(d_list) // 2
sum_d = [sum(d_list[i:i+l-1]) for i in range(l)]

print(min(sum_d))

Submission status: Time Limit Exceeded

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

circum = circum_total[0]
total = circum_total[1]

distances = [int(n) for n in input().split()]

def dist_from_node_forward(node_index, distances):
    forward_distances = distances[node_index:]
    forward_distances.extend([n + circum for n in distances[:node_index]])
    #print(forward_distances)
    dist = 0
    for index in range(1,len(forward_distances)):
        dist += forward_distances[index] - forward_distances[index-1]
    #print(dist)
    return(dist)

def dist_from_node_backward(node_index, distances):
    before = [distances[node_index]]
    before.extend(list(reversed(distances[:node_index])))
    before.append(0)
    #print(before)
    after = list(distances[node_index:])
    after.pop(0)
    #print(after)
    before.extend(list(reversed([n - circum for n in after])))
    #print(before)
    dist = 0
    for index in range(1,len(before)):
        dist += before[index-1] - before[index]
    #print(dist)
    return(dist)

def mindist(node_index, distances):
    return min(dist_from_node_forward(node_index,distances),dist_from_node_backward(node_index,distances))

minimum = circum

for i in range(len(distances)):
    minimum = min(minimum,mindist(i,distances))

print(minimum)

Submission status: Time Limit Exceeded

Solution code:
max,n = map(int,input().split())
l = list(map(int,input().split()))

double = [ i + max for i in l]
ll = l + double

sum = 0
home = 0
ans = 9999999
for i in range(n):
    for j in range(n-1):
        sum += ll[i+j+1] - ll[i+j]
        #print('ll[i+j+1]%d  -  ll[i+j]%d= sum%d    i=%d  j=%d'%(ll[i+j+1],ll[i+j],sum,i,j))

    ans = sum if sum < ans else ans
    #ans = min(ans,sum)
    sum = 0
    
print(ans)

Submission status: Time Limit Exceeded

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

distance = []

for i in range(N-1):
    dis = A[i + 1] - A[i]
    # if i == N - 1:
    #     dis = A[i] - A[1]
    distance.append(dis)

dis = K - A[N - 1] + A[0]
distance.append(dis)

# print(distance)
# print(max(distance))
# print(distance.index(max(distance)))

sum = 0

count = int(len(distance))

for i in range(count):
    if i != distance.index(max(distance)):
        sum += distance[i]

print(sum)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin


inp = stdin.readline

n, k = [int(x) for x in inp().strip().split()]

array = [int(x) for x in inp().strip().split()]

distance = [0]*(k + 2)

for i in range(k - 1):
    distance[1+i] = array[i+1] - array[i]
if array[0] == 0:
    distance[k] = 20-array[k-1]
else:
    distance[k] = abs(array[k - 1] - array[0])
distance[0] = distance[-2]
distance[-1] = distance[1]

minimum = 999999999

for i in range(k + 1):
    total = sum(distance[i:i+k-1])
    if minimum > total:
        minimum = total

print(minimum)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin


inp = stdin.readline

n, k = [int(x) for x in inp().strip().split()]

array = [int(x) for x in inp().strip().split()]

distance = [0]*(len(array) + 2)

for i in range(len(array) - 1):
    distance[1+i] = array[i+1] - array[i]
if array[0] == 0:
    distance[k] = 20-array[k-1]
else:
    distance[k] = abs(array[k - 1] - array[0])
distance[0] = distance[-2]
distance[-1] = distance[1]

minimum = 999999999
for i in range(len(distance) - 1):
    if minimum > sum(distance[i:i+k-1]):
        minimum = sum(distance[i:i+k-1])
print(minimum)

Submission status: Time Limit Exceeded

Solution code:
def main():
    k,n = map(int,input().split())
    posn = list(map(int,input().split()))
    ans = []
    
    if(k<2 and k>1000000):
        main()
    if(n<2 and n>200000):
        main()
    
    posn.sort()
   
        
    
    
    #clockwise
    for i in range(n):
        count = 1
        dist = 0
        current = posn[i]
        
        for j in range(k):
            current+=1
            dist+=1
            if(posn.count(current)==1):
                
                count+=1
            if(current == k):
                current = 0
            if(count==n):
                break
            
        ans.append(dist)
    
    #anti-clockwise
    for i in range(n):
        count = 1
        dist = 0
        current = posn[i]
        
        for j in range(k):
            current-=1
            dist+=1
            if(posn.count(current)==1):
                count+=1
            if(current == 0):
                current = 20
            if(count==n):
                break
            
        ans.append(dist)
    
    
        
    print(min(ans))
    
main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    k,n = map(int,input().split())
    posn = list(map(int,input().split()))
    ans = []
    
    if(k<2 and k>1000000):
        main()
    if(n<2 and n>200000):
        main()
        
   
        
    
    
    #clockwise
    for i in range(n):
        count = 1
        dist = 0
        current = posn[i]
        
        for j in range(k):
            current+=1
            dist+=1
            if(posn.count(current)==1):
                
                count+=1
            if(current == k):
                current = 0
            if(count==n):
                break
            
        ans.append(dist)
    
    #anti-clockwise
    for i in range(n):
        count = 1
        dist = 0
        current = posn[i]
        
        for j in range(k):
            current-=1
            dist+=1
            if(posn.count(current)==1):
                count+=1
            if(current == 0):
                current = 20
            if(count==n):
                break
            
        ans.append(dist)
    
    
        
    print(min(ans))
    
main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    k,n = map(int,input().split())
    posn = list(map(int,input().split()))
    ans = []
    
    #clockwise
    for i in range(n):
        count = 1
        dist = 0
        current = posn[i]
        
        for j in range(k):
            current+=1
            dist+=1
            if(posn.count(current)==1):
                
                count+=1
            if(current == k):
                current = 0
            if(count==n):
                break
            
        ans.append(dist)
    
    #anti-clockwise
    for i in range(n):
        count = 1
        dist = 0
        current = posn[i]
        
        for j in range(k):
            current-=1
            dist+=1
            if(posn.count(current)==1):
                
                count+=1
            if(current == 0):
                current = 20
            if(count==n):
                break
            
        ans.append(dist)
    
    
        
    print(min(ans))
    
main()

Submission status: Time Limit Exceeded

Solution code:
k, n = map(int,input().split())
xs = list(map(int,input().split()))
xs = xs + [x+k for x in xs]

ans = float('inf')
for i in range(n):
    a = xs[i:i+n]
    delta = a[-1] - a[0]
    ans = min(delta, ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
inputText1 = input()
# inputText1 = "20 3"
inputText1List = inputText1.split()
inputNumber1to1 = int(inputText1List[0]) # 20
inputNumber1to2 = int(inputText1List[1]) # 3
inputText2 = input()
# inputText2 = "5 10 15"
inputText2List = inputText2.split()
inputNumber2List = [int(s) for s in inputText2List]
# print(inputNumber2List) #[5, 10, 15]
checkDistance = 0
newList = []
for i in (inputNumber2List):
    if i != 0:
        newList.append(i - inputNumber1to1)

newList.extend(inputNumber2List)

# print(newList) # [-15, -10, -5, 5, 10, 15]
i = 0
count = inputNumber1to2 - 1 # 2(2個っていみ)
# print(count,'count')
breakFlg = False
while True:
    distance = 0
    if i + count >= len(newList):
        break
    for j in range(count):
        distance += abs(newList[i + j] - newList[i +j + 1])
        # print(i,j,'i j',distance)
    if checkDistance == 0:
        # print(checkDistance,'checkDistance')
        checkDistance = distance
    else:
        # print(checkDistance,distance,'redistance')
        if checkDistance > distance:
            checkDistance = distance
            # print("haittyo")
    i += 1


print(checkDistance)

Submission status: Time Limit Exceeded

Solution code:
P, N = list(map(int, input().split()))
arr = list(map(int, input().split()))
arr.sort()
mn = arr[-1] - arr[0]
for i in range(N):
    val = arr.pop(0)
    arr.append(val + P)
    mn = min([mn, arr[-1] - arr[0]])
print(mn)

Submission status: Time Limit Exceeded

Solution code:
K, N = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
ans = []
for i in range(len(A)):
    ans.append(max(A) - min(A))
    A[i] += K

print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
x=list(map(int,input().split()))
xx=[]
for i in x:
    xx.append(i)
    xx.append(i-k)
y=sorted(xx)
z=[]
for i in range(n+1):
    z.append(max(y[i:i+n])-min(y[i:i+n]))
print(min(z))

Submission status: Time Limit Exceeded

Solution code:
def calc_sub(arg, start):
  global n,k
  sub = 0
  for i in range(n):
    if i != 0:
      idx = start + i
      if idx < n:
        sub += arg[idx] - arg[idx-1]
      else:
        idx = idx - n
        if idx == 0:
          sub += arg[0] + (k - arg[n-1])
        else:
          sub += arg[idx] - arg[idx-1]
        
  return sub

def calc_sub_r(arg, start):
  global n,k
  sub = 0
  for i in reversed(range(0, n)):
    idx = start + i
    idx = idx - n if idx >= n else idx
    if idx == n-1:
      sub += (k - arg[idx]) + arg[0]
    else:
      sub += arg[idx+1] - arg[idx]
  return sub


k, n = map(int, input().split())
a = input().split()
l_si_i = [int(s) for s in a]
#print(l_si_i)

#aaa = calc_sub(l_si_i, 2)
#bbb = calc_sub_r(l_si_i, 2)
#print(aaa)
#print(bbb)


min = 10000000
for i in range(n):
  ret = calc_sub(l_si_i,i)
  if min > ret:
    min = ret
    
  ret = calc_sub_r(l_si_i, i)
  if min > ret:
    min = ret
#  l_si_i.append(l_si_i.pop(0))

print(min)

Submission status: Time Limit Exceeded

Solution code:
K,N=map(int,input().split())
A=list(int(i) for i in input().split())
A.append(A[0])
#print(A)

a=[]
for i in range(N-1):
  a.append(abs(A[i]-A[i+1]))
  #print(a)
a.append(abs(K-A[N-1]))
#print(a)

ans=1000
tmp=0
for i in range(N):
  tmp=sum(a)-a[i]
  if tmp<ans:  
    ans=tmp
    #print(tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def calc_sub(arg, start):
  global n,k
  sub = 0
  for i in range(n):
    if i != 0:
      idx = start + i
      if idx < n:
        sub += arg[idx] - arg[idx-1]
      else:
        idx = idx - n
        if idx == 0:
          sub += arg[0] + (k - arg[n-1])
        else:
          sub += arg[idx] - arg[idx-1]
        
  return sub

def calc_sub_r(arg, start):
  global n,k
  sub = 0
  for i in reversed(range(0, n)):
    idx = start + i
    idx = idx - n if idx >= n else idx
    if idx == n-1:
      sub += (k - arg[idx]) + arg[0]
    else:
      sub += arg[idx+1] - arg[idx]
  return sub


k, n = map(int, input().split())
a = input().split()
l_si_i = [int(s) for s in a]
#print(l_si_i)

#aaa = calc_sub(l_si_i, 2)
#bbb = calc_sub_r(l_si_i, 2)
#print(aaa)
#print(bbb)


min = 10000000
for i in range(n):
  ret = calc_sub(l_si_i,i)
  if min > ret:
    min = ret
    
  ret = calc_sub_r(l_si_i, i)
  if min > ret:
    min = ret
    
  l_si_i.append(l_si_i.pop(0))

print(min)

Submission status: Time Limit Exceeded

Solution code:
def main():
    k,n=map(int,input().split())
    a=list(map(int,input().split()))
    resf=10**7
    for i in a:
        if i==a[0]:
            res=min(a[-1]-a[0],k-(a[1]-a[0]))
        elif i==a[-1]:
            res=min(k-(a[-1]-a[-2]),a[-1]-a[0])
        else:
            if k-(a[a.index(i)+1]-i)<=k-(i-a[a.index(i)-1]):
                res=k-(a[a.index(i)+1]-i)
            else:
                res=k-(i-a[a.index(i)-1])
        if resf>=res:
            resf=res
    print(resf)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    k,n=map(int,input().split())
    a=list(map(int,input().split()))
    resf=10**7
    for i in a:
        if i==a[0]:
            res=min(a[-1]-a[0],k-(a[1]-a[0]))
        elif i==a[-1]:
            res=min(k-(a[-1]-a[-2]),a[-1]-a[0])
        else:
            res=min(k-(a[a.index(i)+1]-i),k-(i-a[a.index(i)-1]))
        resf=min(resf,res)
    print(resf)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
while True:
  a = 1

Submission status: Time Limit Exceeded

Solution code:
k, n = map(int, input().split())
house = list(map(int, input().split()))
load = [0]*k

for i in house:
    load[i] = 1


def check(lst):
    return k - lst.index(1) -1


best_way = k
for i in house:
    right = load[i+1:]
    left = load[:i]
    a_way = right + left
    way = min(check(a_way), check(a_way[::-1]))
    if way < best_way:
        best_way = way

print(best_way)

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
a=list(map(int,input().split()))
resf=10**8
for i in a:
    if i==a[0]:
        res=min(a[-1]-a[0],k-(a[1]-a[0]))
    elif i==a[-1]:
        res=min(k-(a[-1]-a[-2]),a[-1]-a[0])
    else:
        res=min(k-(a[a.index(i)+1]-i),k-(i-a[a.index(i)-1]))
    resf=min(resf,res)
print(resf)

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
a=list(map(int,input().split()))
resf=10**8
for i in a:
    if i==a[0]:
        res=min(a[-1]-a[0],k-(a[1]-a[0]))
    elif i==a[-1]:
        res=min(k-(a[-1]-a[-2]),a[-1]-a[0])
    else:
        res=min(k-(a[a.index(i)+1]-i),k-(i-a[a.index(i)-1]))
    resf=min(resf,res)
print(resf)

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int,input().split())
N = N-1
A = list(map(int, input().split()))
A_d = [ A[i+1]-A[i] for i in range(0, len(A)-1)]
A_d.append(K-A[-1]+A[0])
A_d2 = (A_d+A_d[1:])*2
res = K
for i in range(len(A_d2)-1):
    s = sum(A_d2[i:i+N])
    res = s if res > s else res
print(res)

Submission status: Time Limit Exceeded

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

for i in range(0, N): 
        for j in range(i + 1, N): 
            if A[i] + A[j] == K: 
                if A[i] > A[j]:
                    print(A[i] - A[j])
                else:
                    print(A[j] - A[i])

Submission status: Time Limit Exceeded

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

dis = 0
done = [A[0]]
not_done = A[1:N]

while True:
    min_d = 1e6
    for a in done:
        for b in range(len(not_done)):
            if a>b:
                d = min(abs(a-not_done[b]), abs(a-not_done[b]-K))
            else:
                d = min(abs(a-not_done[b]), abs(a-not_done[b]+K))
            min_d = min(d, min_d)
            min_idx = b
    dis += min_d
    done.append(not_done.pop(min_idx))
    if len(not_done) ==0:
        break
print(dis)

Submission status: Time Limit Exceeded

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

l=[]
distance=0
for i in range(1,n):
    distance += (a[-i]-a[-i-1])
l.append(distance)
# print(l)

a_minus = [i-k for i in a if i != 0]
a_minus.sort(reverse=True)
# print(a_minus)

for j in range(n-1):
    tmp = a[:(-j-1)]
    tmp.extend(a_minus[:n-len(tmp)])
    tmp.sort(reverse=True)
    # print(tmp)
    d=0
    for k in range(len(tmp)-1):
        if tmp[k]>0:
            if tmp[k+1]>0:
                # print("++")
                d+=abs(tmp[k])-abs(tmp[k+1])
            else:
                d+=abs(tmp[k])+abs(tmp[k+1])
        else:
            # print("--")
            d+=abs(abs(tmp[k])-abs(tmp[k+1]))
    l.append(d)
print(min(l))

Submission status: Time Limit Exceeded

Solution code:
k,n = map(int,input().split())
l = list(map(int,input().split()))
l.sort()


dist = []
for i in range(1,n) :
    x = l[i] - l[i-1]
    if x >= 0 :
        dist.append(x)
    else :
        dist.append(x + k)

if l[0] - l[-1] >= 0 :
    dist.append(l[0] - l[-1])
else :
    dist.append(l[0] - l[-1] + k)


summin = 99999999
sum = 0
for i in range(0,len(dist)) :
    sum = 0
    for j in range(i,i+len(dist)-1) :
        sum += dist[j%len(dist)]
    if(sum < summin) :
        summin = sum 
    #print(sum)

#print(dist)
print(summin)

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int,input().split())
N = N-1
A = list(map(int, input().split()))
A_d = [ A[i+1]-A[i] for i in range(0, len(A)-1)]
A_d.append(K-A[-1]+A[0])
A_d2 = (A_d+A_d[1:])*2
res = K
for i in range(len(A_d2)-1):
    res = sum(A_d2[i:i+N]) if res > sum(A_d2[i:i+N]) else res
print(res)

Submission status: Time Limit Exceeded

Solution code:
def around(K,A):
    N2 = A.pop(0)
    A.append(N2+K)
    return A

K,N = map(int, input().split(" "))
A = list(map(int, input().split(" ")))

X = 0
X_min = 1000000000
for j in range(0,len(A)):
    X=0
#     print(A)
    X = A[len(A)-1] - A[0]
#     print(X)
#     for i in range(0,len(A)-1): #i番目の家からスタート
#         X += A[i+1] - A[i]
#         if X > X_min:
#             i=0
#             break
#     if i == len(A)-2:
#     print(X)
    if X_min > X:
        X_min = X
    A=around(K,A)
#     print(X_min)
    
print(X_min)

Submission status: Time Limit Exceeded

Solution code:
k, n = map(int, input().split())
l = list(map(int, input().split()))
c = n*(n-1)//(n-1)
s = [0 for _ in range(c)]
for i in range(c):
  for j in range(n-1):
    if l[j+1] == 0:
      s[i] += abs(k-l[j])
    else:
      s[i] += abs(l[j+1]-l[j])
  temp = l.pop(0)
  l.append(temp)
print(min(s))

Submission status: Time Limit Exceeded

Solution code:
k, n = map(int, input().split())
house = list(map(int, input().split()))
load = [0]*k

for i in house:
    load[i] = 1

def check(lst):
    cnt = 0
    way = 0
    for i in lst:
        way += 1
        if i == 1:
            cnt += 1
        if cnt == n-1:
            break

    return way


best_way = k
for i in house:
    right = load[i+1:]
    left = load[:i]
    right_way = right + left
    left_way = left[::-1] + right[::-1]
    way = min(check(right_way), check(left_way))
    if way < best_way:
        best_way = way

print(best_way)

Submission status: Time Limit Exceeded

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

d = [a[i] - a[i-1] for i in range(1, n)]
d.insert(0, a[0])
d.append(k - a[-1])
sum_d = sum(d)

most_min_path = 10000

for i in range(n):
    if i == 0:
        normal_ck = sum_d - d[i] - d[-1]
        reverse_ck = sum_d - d[i+1]
    elif i == n - 1:
        normal_ck = sum_d - d[i]
        reverse_ck = sum_d - d[i+1] - d[0]
    elif 0 < i < n - 1:
        normal_ck = sum(d) - d[i]
        reverse_ck = sum(d) - d[i+1]

    min_ck = normal_ck if normal_ck < reverse_ck else reverse_ck
    if most_min_path > min_ck:
        most_min_path = min_ck

print(most_min_path)

Submission status: Time Limit Exceeded

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

d = [a[i] - a[i-1] for i in range(1, n)]
d.insert(0, a[0])
d.append(k - a[-1])
sum_d = sum(d)

most_min_path = 10000

for i in range(n):
    if i == 0:
        normal_ck = sum_d - d[i] - d[-1]
        reverse_ck = sum_d - d[i+1]
    elif i == n - 1:
        normal_ck = sum(d) - d[i]
        reverse_ck = sum(d) - d[i+1] - d[0]
    elif 0 < i < n - 1:
        normal_ck =  sum(d) - d[i]
        reverse_ck = sum(d) - d[i+1]

    min_ck = normal_ck if normal_ck < reverse_ck else reverse_ck
    if most_min_path > min_ck:
        most_min_path = min_ck

print(most_min_path)

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int, input().split())
list_str = input().split()
Kyori_list = [int(s) for s in list_str]
len_list = []
for i in range(len(Kyori_list)):
    if i < (len(Kyori_list) -1):
        len_list.append(Kyori_list[i+1] - Kyori_list[i])
    else:
        len_list.append(K+Kyori_list[0] - Kyori_list[i])


min_ptn = K
for i in range(len(len_list)):
    len_ptn =0
    for j in range(len(len_list)):
        if i != j:
            len_ptn += len_list[j]
    if min_ptn > len_ptn:
        min_ptn = len_ptn

print(min_ptn)

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int,input().split())
N = N-1
A = list(map(int, input().split()))
A_d = [ A[i+1]-A[i] for i in range(0, len(A)-1)]
A_d.append(K-A[-1]+A[0])
A_d2 = (A_d+A_d[1:])*2
res = K
for i in range(len(A_d2)-1):
    if res > sum(A_d2[i:i+N]):
        res = sum(A_d2[i:i+N])
print(res)

Submission status: Time Limit Exceeded

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

d = [a[i] - a[i-1] for i in range(1, n)]
d.insert(0, a[0])
d.append(k - a[-1])
sum_d = sum(d)

most_min_path = 10000

for i in range(n):
    if i == 0:
        normal_ck = sum_d - d[i] - d[-1]
        reverse_ck = sum_d - d[i+1]
    elif i == n - 1:
        normal_ck = sum(d) - d[i]
        reverse_ck = sum(d) - d[i+1] - d[0]
    else:
        normal_ck = sum(d) - d[i]
        reverse_ck = sum(d) - d[i+1]

    min_ck = normal_ck if normal_ck < reverse_ck else reverse_ck
    if most_min_path > min_ck:
        most_min_path = min_ck

print(most_min_path)

Submission status: Time Limit Exceeded

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

minv = 9999
for i in range(len(a)):
        t = 0
        s = i
        e = s + 1
        for j in range(len(a) - 1):
                if s >= len(a):
                        s = len(a) - s
                if e >= len(a):
                        e = len(a) - e
                if s > e:
                        t = t + abs((k - a[s]) + a[e])
                else:
                        t = t + abs(a[e] - a[s])

                s = s + 1
                e = e + 1
        if minv > t:
                minv = t
print(minv)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import numpy as np

K, N = map(int, input().split())
AS = list(map(int, input().split()))

routes = []
cycle = itertools.cycle(AS)

for i in range(0, N):
    route = []
    l = 0
    for j in range(0, N):
        d = next(cycle)
        if d < l:
            d = K + d
        l = d
        route.append(d)

    routes.append(route)
    next(cycle)

def distance(route):
    route = np.array(route)
    return sum(np.diff(route, n=1))

print(min(list(map(distance, routes))))

Submission status: Time Limit Exceeded

Solution code:
k, n = map(int, input().split())
a_list = list(map(int, input().split()))
ans = k
for i in a_list:
    seq_list = a_list
    for j in range(n):
        if i == 0 and a_list[j] > k / 2:
            seq_list[j] = a_list[j] - k
        else:
            seq_list[j] = a_list[j] - i
    max_a = max(seq_list)
    min_a = min(seq_list)
    seq_dis = max_a - min_a
    ans = min(seq_dis, ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
l=list(map(int,input().split()))
ans=1000000
for i in range(n-1):
  d = 0
  for j in range(n):
    if i!=j:
      d+=min(abs(l[j]-l[i]),abs(k-l[j]))
  if ans > d:
    ans=d
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

K, N = [int(i) for i in input().split()]
A = deque(map(int, input().split()))
A.appendleft(0)
A.append(K)
C = np.array(A)
diff = np.diff(C)
if N == 2:
    print(A[1] - A[0])
else:
    # maxIndexが1以上の場合（逆周りしようとしている場合)、maxの辺と、1要素目の辺+最終辺(Kまで)の辺を比べる必要がある
    maxValue = np.max(diff)
    if maxValue >= diff[0] + diff[len(diff) - 1]:
        # こっちの場合、逆順の方が得
        # 逆順の場合、maxの辺のみ消せる
        print(diff.sum() - maxValue)
    else:
        # 正常の場合、1個目の辺と最後の辺が要らない
       print(diff.sum() - diff[0] - diff[len(diff) - 1])

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
l=list(map(int,input().split()))
ans=[]
for i in range(len(l)):
  ans.append(sum(min(abs(l[j]-l[i]),abs(k-l[j])) for j in range(len(l)) if i!=j))
print(min(ans))

Submission status: Time Limit Exceeded

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

dis = 0
done = [A[0]]
not_done = A[1:N]

while True:
    min_d = 1e6
    for a in done:
        for b in range(len(not_done)):
            if a>b:
                d = min(abs(a-not_done[b]), abs(a-not_done[b]-20))
            else:
                d = min(abs(a-not_done[b]), abs(a-not_done[b]+20))
            min_d = min(d, min_d)
            min_idx = b
    dis += min_d
    done.append(not_done.pop(min_idx))
    if len(not_done) ==0:
        break
print(dis)

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int,input().split())
i = tuple(map(int, input().split()))
ans_tuple = [(max(tuple(map(lambda z: (z - i[x])%K , i)))-min(tuple(map(lambda z: (z - i[x])%K , i)))) for x in range(N)]
print(min(ans_tuple))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

dist = []
dist.append(a[1]-a[0])

for num in range(1, len(a)):
  if num == len(a) - 1:
    dist.append(k-a[num]+a[0])
  else:
    dist.append(a[num+1]-a[num])
#print(dist)
dist = np.array(dist)

min_index = [i for i, v in enumerate(dist) if v == min(dist)]
s = np.sum(dist)
result = []
for start_index in min_index:
  if start_index == 0:
    result.append(s - dist[len(dist)-1])
    result.append(s - dist[start_index+1])
  elif start_index == len(dist)-1:
    result.append(s - dist[start_index-1])
    result.append(s - dist[0])
  else:
    result.append(s - dist[start_index-1])
    result.append(s - dist[start_index+1])
print(min(result))

Submission status: Time Limit Exceeded

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

dis = 0
done = [A[0]]
not_done = A[1:N]

while True:
    min_d = 1e6
    for a in done:
        for b in range(len(not_done)):
            if a>b:
                d = min(abs(a-not_done[b]), abs(a-not_done[b]-20))
            else:
                d = min(abs(a-not_done[b]), abs(a-not_done[b]+20))
            min_d = min(d, min_d)
            min_idx = b
    dis += min_d
    done.append(not_done.pop(b))
    if len(not_done) ==0:
        break
print(dis)

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
l=list(map(int,input().split()))
ans=1000000
for i in range(n):
  d = 0
  for j in range(n):
    if i!=j:
    	d+=min(abs(l[j]-l[i]),abs(k-l[j]))
  if ans > d:
    ans=d
print(ans)

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())

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

mindis=0

for i in range(len(a)):
  cw=0
  ncw=a[i]
  nccw=a[i]
  ccw=0

  for j in range(1,len(a)):
    r=0
    q=0

    if ncw>a[(i+j)%len(a)]:
      cw+=((k-ncw)+a[(i+j)%len(a)])
      r=-1
    if nccw<a[i-j]:
      ccw+=(nccw+(k-a[i-j]))
      q=-1
    if r==0:
      cw+=abs(ncw-a[(i+j)%len(a)])
    if q==0:
      ccw+=abs(nccw-a[i-j])

    ncw=a[(i+j)%len(a)]
    nccw=a[i-j]
    #print(cw,ccw)

  if mindis==0:
    if cw<ccw:
      mindis=cw
    else:
      mindis=ccw

  if mindis>cw:
    mindis=cw

  if mindis>ccw:
    mindis=ccw
  #print()

print(mindis)

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int,input().split())
i = list(map(int, input().split()))
ans_list = []
ans_list = [(max(list(map(lambda z: (z - i[x])%K , i)))-min(list(map(lambda z: (z - i[x])%K , i)))) for x in range(N)]
print(min(ans_list))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

K, N = [int(i) for i in input().split()]
A = deque(map(int, input().split()))
A.appendleft(0)
A.append(K)
C = np.array(A)
diff = np.diff(C)
if N == 2:
    print(A[1] - A[0])
else:
    # maxIndexが1以上の場合（逆周りしようとしている場合)、maxの辺と、1要素目の辺+最終辺(Kまで)の辺を比べる必要がある
    maxValue = np.max(diff)
    maxIndex = np.argmax(diff)
    if maxIndex > 1:
        if maxValue >= diff[0] + diff[len(diff) - 1]:
            # こっちの場合、逆順の方が得
            # # 逆順の場合、maxの辺のみ消せる
            print(diff.sum() - maxValue)
        else:
           # 正常の場合、1個目の辺と最後の辺が要らない
           print(diff.sum() - diff[0] - diff[len(diff) - 1])
    else:
        # 正常の場合、1個目の辺と最後の辺が要らない
        print(diff.sum() - maxValue - diff[len(diff) - 1])

Submission status: Time Limit Exceeded

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

dist = [0] * n
for i in range(n):
    for j in range(i + 1, n):
        dist_tmp = a[j] - a[i]
        if dist_tmp > (k / 2.0):
            dist_tmp = k - dist_tmp
        dist[i] += dist_tmp
        dist[j] += dist_tmp

ans = dist[0]
for d in dist:
    ans = min(ans, d)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int, input().split())
A = list(map(int, input().split()))
ans = 0
for i in range(N-1):
  for j in range(i+1,N):
    a = abs(A[i]-A[j])
    ans = max(ans, min(a, K-a))
print (K-ans)

Submission status: Time Limit Exceeded

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

A.sort()

r = [y-x for x, y in zip(A, A[1:]+[K])]

ans = 10**9
for i in range(len(A)):
    temp = sum(r[:N-1])
    if ans > temp:
        ans = temp
    r.append(r.pop(0))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

K, N = [int(i) for i in input().split()]
A = list(map(int, input().split()))
B = deque(A)
B.appendleft(0)
B.append(K)
C = np.array(B)
diff = np.diff(C)
if N == 2:
    print(A[1] - A[0])
else:
    # maxIndexが1以上の場合（逆周りしようとしている場合)、maxの辺と、1要素目の辺+最終辺(Kまで)の辺を比べる必要がある
    maxValue = np.max(diff)
    maxIndex = np.argmax(diff)
    if maxIndex > 1:
        if maxValue >= diff[0] + diff[len(diff) - 1]:
            # こっちの場合、逆順の方が得
            # # 逆順の場合、maxの辺のみ消せる
            print(diff.sum() - maxValue)
        else:
           # 正常の場合、1個目の辺と最後の辺が要らない
           print(diff.sum() - diff[0] - diff[len(diff) - 1])
    else:
        # 正常の場合、1個目の辺と最後の辺が要らない
        print(diff.sum() - maxValue - diff[len(diff) - 1])