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: Wrong Answer

Solution code:
#author : dokueki

import sys


def IOE():
    sys.stdin = open("input.txt", "r")
    sys.stdout = open("output.txt", "w")


def main():
    k, n = map(int, sys.stdin.readline().split())
    a = list(map(int, sys.stdin.readline().split()))
    print(a[-1]-a[0])


if __name__ == "__main__":
    #IOE()
    main()

Submission status: Wrong Answer

Solution code:
K, N = map(int, input().split())
A = list(map(int, input().split()))
d = []
for i in A:
    house = A[N - 1] - K
    d.append(i - house)
    house = i
print(K - min(d))

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
l = list(map(int,input().split()))
ans = max(l)-min(l)
print(ans)

Submission status: Wrong Answer

Solution code:
k,n = map(int,input().split())
a = list(map(int, input().split(' ')))
x = k - a[-1]
for i in range(n-1):
    y = a[i+1]-a[i]
    if y > x:
        x = y
print(k-x)

Submission status: Wrong Answer

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

a = list(map(int,input().split()))
k_diff = []

for i in range(1,n):
    k_diff.append(abs(a[i-1] - a[i]))

k_diff.append(k - a[-1])

print(k - max(k_diff))

Submission status: Wrong Answer

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

ans = A[N-1] - A[0]
for i in range(N-1):
  ans = min(ans, K - A[i+1] - A[i])
print(ans)

Submission status: Wrong Answer

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

ans = sum(A)

ans -= max((A[(i + 1) % N] - A[i]) % K for i in range(N))

print(ans)

Submission status: Wrong Answer

Solution code:
K,N=map(int,input().split())
A=list(map(int,input().split()))
A.sort()
ans=A[-1]-A[0]
for i in range(N):
    if A[i]>K//2:
        A[i]-=K
A.sort()
print(min(ans, A[-1]-A[0]))

Submission status: Wrong Answer

Solution code:
#!python3

iim = lambda: map(int, input().rstrip().split())

def resolve():
    N, K = iim()
    A = list(iim())

    d1 = 0
    for i in range(K-1):
        d2 = A[i+1] - A[i]
        d1 = max(d1, d2)
    d1 = max(d1, N-A[-1]+A[0])
    print(d1)


if __name__ == "__main__":
    resolve()

Submission status: Wrong Answer

Solution code:
K, N = map(int, input().split())
A = [int(x) for x in input().split()]
A.sort()
ans = 0
for i in range(N-1):
  ans += A[i+1] - A[i]
print(ans)

Submission status: Wrong Answer

Solution code:
k, n = map(int, input().split())
a = list(map(int, input().split()))
tmp = a[0] +  k - a[-1]
for i in range(1, n):
    a[i] -= a[i - 1]
a[0] = tmp
# print(a)
print(k - max(a))

Submission status: Wrong Answer

Solution code:
k,n = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
maxdis = 0
pre = 0
for dis in a:
    t = dis - pre
    pre = dis
    if t > maxdis:
        maxdis = t
maxdis = max(maxdis, k - a[-1])
print(k-maxdis)

Submission status: Wrong Answer

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

ans=[]
for i in range(n-1):
    ans.append(a[i+1]-a[i])

ans.append(k-a[-1])
ans.sort()
print(sum(ans[:-1]))

Submission status: Wrong Answer

Solution code:
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

k, n, *lst = map(int, read().split())
lst.sort()
dis = 0
for i in range(n):
    if i == 0:
        dis = max(dis, lst[-1] - lst[0])
    else:
        dis = max(dis, lst[i] - lst[i - 1])

dis = min(dis, k - dis)
print(dis)

Submission status: Wrong Answer

Solution code:
def main():
    K,N,*A=map(int, open(0).read().split())
    A+=[A[0]+K,A[1]+K]
    print(K-min(abs(A[i+2]-A[i]) for i in range(N)))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
k,n = map(int,input().split())
a = list(map(int,input().split()))
ans = [0]*n
for i in range(n-1):
    ans[i] = a[i+1] - a[i]
ans[-1] = (k-a[-1])
print(sum(ans) - max(ans) )

Submission status: Wrong Answer

Solution code:
# S = input()

# if S[2] == S[3] and S[4] == S[5]:
#     print('Yes')
# else:
#     print('No')

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

A.sort()
x = K - A[-1] + A[0]
for i in range(N - 1):
    x = max(A[i + 1] - A[i], x)

print(x)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input=sys.stdin.readline
    k,n=map(int,input().split())
    A=list(map(int,input().split()))
    m=0
    for i in range(n-1):
        m=max(m,A[i+1]-A[i])
    m=max(m,A[0]+k-A[-1])
    print(m)
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
k, n = list(map(int, input().split()))
a = list(map(int, input().split()))
a.append(k)
b = []
for i in range(n):
  b.append(a[i + 1] - a[i])

b.sort()

print(k - b[0] - b[1])

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline

def main():
    L,N = map(int,input().split())
    a = list(map(int,input().split()))
    
    ans = 0
    for i in range(N-1):
        ans = max(ans,a[i+1]-a[i])
        
    ans = max(ans,N+a[0]-a[-1])
    
    print(L-ans)
    
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
k,n = map(int,input().split())
a = list(map(int,input().split()))
b = [0] * n
for i in range(n-1):
     b[i] = a[i+1] - a[i]
b[n-1] = k - a[n-1]
print(sum(b)-max(b))

Submission status: Wrong Answer

Solution code:
K,N = map(int, input().split())
As  = list(map(int, input().split()))
Bs = As + [K]
diff = [abs(Bs[i+1]-Bs[i]) for i in range(N)]

mx = 0
print(sum(diff) - max(diff))

Submission status: Wrong Answer

Solution code:
k,n = map(int,input().split())
A = list(map(int,input().split()))
r = 0
for i in range(1, n):
    r = max(r, A[i]-A[i-1])
print(k-r)

Submission status: Wrong Answer

Solution code:
K,N = map(int,input().split())
A = list(map(int,input().split()))
result = 0
for i in range(N-1):
    result += A[i+1] - A[i]
print(result)

Submission status: Wrong Answer

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


import numpy as np

d = np.diff(a)
d = np.append(d, k - a[-1] + a[0])

print(k - np.sum(np.sort(d)[:-1]))

Submission status: Wrong Answer

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

A = list(map(int, input().split()))
A.append(A[0])

a = [A[i + 1] - A[i] for i in range(N - 1)]
a.append(K + A[0] - A[-1])

a.sort()
print(sum(a[:-1]))

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int, input().split())
A = sorted(map(int, input().split()))
assert len(A) == N


dists = []
for i,start in enumerate(A):
  # 右回り
  posR = max([a + K for a in A[:i]] + A[i+1:])
  # 左回り
  posL = min(A[:i] + [a - K for a in A[i+1:]])
  dists.append(min(posR - start, - posL + start))
print(min(dists))

Submission status: Time Limit Exceeded

Solution code:
A, B = map(int, input().split())

i = 1

while True:
  
  if i % A == 0 and i % B == 0:
    print(i)
    break
    
  i += max(A, B)

Submission status: Time Limit Exceeded

Solution code:
A, B = map(int, input().split())

i = 1

while True:
  
  if i % A == 0 and i % B == 0:
    print(i)
    exit()
    
  i += max(A, B)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

A = A + list(map(lambda x: x+K, A))

ans = float('inf')
for i in range(N):
    cost = 0
    for j in range(i+1, N+i):
         cost += A[j] - A[j-1]
    ans = min(ans, cost)

print(ans)

Submission status: Time Limit Exceeded

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

    # 距離の最大値を求める．
    max_dist = 0
    for i in range(N):
        for j in range(N):
            # 時計回りの距離
            dist1 = abs(A[i] - A[j])
            # 反時計回りの距離
            dist2 = K - dist1
            if(dist1 < dist2):
                dist_tmp = dist1
                flg = True
            else:
                dist_tmp = dist2
                flg = False
            if(dist_tmp > max_dist):
                max_dist = dist_tmp
                max_index = i, j
                max_flg = flg
    k = 0
    for k in range(N):
        if(k == max_index[0] or k == max_index[1]):
            continue
        if(abs(A[max_index[0]] - A[k] <= max_dist and  abs(A[max_index[1]] - A[k] <= max_dist))):
            if(flg):
                ans = max_dist
            else:
                ans = K - max_dist
        else:
            if(flg):
                ans = K - max_dist
            else:
                ans = max_dist
        break
    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
#C - Traveling Salesman around Lake WA(ヒント)
K,N = map(int,input().split())
A = list(map(int, input().split()))

A[N+1:] = A#Aを二回繰り返して円を表現
A_reverse = reversed(A)

distance_list = []
for i in range(N):#スタート地点の数
    distance = 0
    for j in range(N-1):#道の数
        distance += abs(A[i+1] - A[i])#道の距離
    distance_list.append(distance)
for k in range(N):#逆回りについて
    distance = 0
    for j in range(N-1):
        distance += abs(A[i+1] - A[i])
    distance_list.append(distance)
print(min(distance_list))

Submission status: Time Limit Exceeded

Solution code:


K,N = list(map(int,input().split()))
A = list(map(int,input().split()))
A.append(K)
B = []
for i in range(N):
    B.append(abs(A[i]-A[i+1]))
#print(B)
ans = K
for i in range(N):
    ans = min(ans,sum(B)-B[i])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
line1 = input()
line2 = input()

aryLine1 = line1.split()
aryLine2 = line2.split()

K = int(aryLine1[0]);
N = int(aryLine1[1]);

ans = 0

for i in range(0, N):
    temp1 = int(aryLine2[i])
    for j in range(0, N):
        temp2 = int(aryLine2[j])

        if temp1 > temp2:
            ans1 = temp1 - temp2
            ans2 = temp2 - temp1 + K
        else:
            ans1 = temp2 - temp1
            ans2 = temp1 - temp2 + K

        if ans1 > ans2:
            tempans = ans2
        else:
            tempans = ans1

        if tempans > ans:
            ans = tempans

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, k = map(int,input().split())
a = list(map(int,input().split()))
tmp = list(map(lambda x:x+n,a))
a = a + tmp
l = len(a)

b=[0]*(l-1)
for i in range(l-1):
  b[i] = a[i+1]-a[i]

ans = 10**9
for j in range(l-k+1):
  ans = min(ans,sum(b[j:j+k-1]))
print(ans)

Submission status: Time Limit Exceeded

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

dist = []
for i in range(N-1):
    dist.append(a[i + 1] - a[i])
dist.append(a[0] + (K - a[-1]))

total = []
for i in range(len(dist)):
    total.append(sum(dist) - dist[i])

print(min(total))

Submission status: Time Limit Exceeded

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

d = [0] * (len(a)) 

for i in range(n):
    if i == 0:
        d[i] = k - a[-1]
        continue
    d[i] = a[i]-a[i-1]

d += d
ans = 1001001001
for i in range(len(d)-n+1):
    ans = min(ans, sum(d[i:i+n-1]))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
a=list(map(int,input().split()))
d=0
for i in range(n-1):
    d=max(sorted(a)[i+1]-sorted(a)[i],d)
d=max(k+sorted(a)[0]-sorted(a)[n-1],d)
print(k-d)

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
a=list(map(int,input().split()))
d=[0]*n
for i in range(n-1):
    d[i]=sorted(a)[i+1]-sorted(a)[i]
d[-1]=k+sorted(a)[0]-sorted(a)[n-1]
print(k-max(d))

Submission status: Time Limit Exceeded

Solution code:
k,n = map(int,input().split())
a = list(map(int,input().split()))
l = k - a[n-1] + a[0]
t = 0

for i in range(n):
    p = 0
    j = i + 1

    while True:
        if j == n:
            j = 0

        if j == i:
            break

        if j == 0:
            p += l
        else:
            p += a[j] - a[j-1]

        j += 1

    if t == 0:
        t = p
    else:
        if t > p:
            t = p

print(t)

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int, input().split())
Alist = list(map(int, input().split()))
  
#for each house, traverse clock/anti-clock wise
Alen = len(Alist)
min_distance = 10000000
for s in range(Alen):
  distance = 0
  start_p = s
  current_p = s
  next_p = 0 # random number
  #clock-wise
  while (True):
    # calculate next point
    if (current_p == (Alen-1)):
      next_p = 0
    else:
      next_p = current_p+1
    # finish if reached to start point again
    if (next_p == start_p):
      break
    # add distance from current to next point
    if (next_p == 0):
      distance += (K-Alist[current_p]+Alist[next_p])
    else:
      distance += (Alist[next_p]-Alist[current_p])
    # move to next point
    current_p = next_p
   
  if (distance < min_distance):
    min_distance = distance
  #anti- clock-wise
  #distance = 0
  #while (True):
  #  if (s == 0):
   #   distance += (Alist[s]+(K-Alist[s-1]))
   # else:
   #   distance += (Alist[s]-Alist[s-1])
   # s -= 1
  #  if ( (s-1) == ((-1*Alen)+start_p) ):
   #   break
 # print("anti"+str(distance))
  #if (distance < min_distance):
   # min_distance = distance

print(min_distance)

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations

k, n = map(int,input().split())
ans=0
a= list(map(int,input().split()))
differences=[]
for a, b in combinations(a, 2):
    if a==0 or b==0:
        differences.append(min(abs(a-b),abs(k-b)))
    else:
        differences.append(abs(a-b))
differences.sort()
for i in range(n-1):
    ans+=differences[i]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int, input().split())
A = list(map(int, input().split()))
x = A[:]
k = -1
for _ in range(N):
    x = x[1:] + x[:1]
    diff = sum([min(K - abs(x[i] - x[i+1]), abs(x[i] - x[i+1])) for i in range(N - 1)])
    if k == -1 or k > diff:
        k = diff
print(k)

Submission status: Time Limit Exceeded

Solution code:
k, n = map(int, input().split())
a = list(map(int, input().split()))
b = []
for i in range(1, n):
  b.append(abs(a[i]-a[i-1]))
  b.append(k+a[0]-a[n-1])
  b.sort()
  p = b[-1]

print(k-p)

Submission status: Time Limit Exceeded

Solution code:
k, n = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
b = []
for i in range(1, n):
  b.append(a[i]-a[i-1])
  b.append(k+a[0]-a[n-1])
  b.sort()
  p = b[-1]

print(k-p)

Submission status: Time Limit Exceeded

Solution code:
k, n = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
b = []
c = abs(k+a[0]-a[n-1])
for i in range(1, n):
  b.append(abs(a[i] - a[i-1]))
  b.sort()
  p = b[-1]

if p > c:
  print(k - p)
else:
  print(k - c)

Submission status: Time Limit Exceeded

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

#k,n = 20,3
#a = [0,5 ,15]
a = list(map(lambda x : x - min(a) , a))

s = [k - a[n-1]]
for i in range(1,n):
  s.append(a[i]-a[i-1])

print(k - max(s))

Submission status: Time Limit Exceeded

Solution code:
i = list(map(int, input().split()))
K = i[0]
N = i[1]

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

m = K

for i in range(N):
  for j in range(i,N):
    t = max(abs(s[i] - s[j]), K - abs(s[i] - s[j]))
    if t <= m:
      m = t
      
print(m)

Submission status: Time Limit Exceeded

Solution code:
i = list(map(int, input().split()))
K = i[0]
N = i[1]

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

m = K

for i in range(N):
  for j in range(N):
    t = max(abs(s[i] - s[j]), K - abs(s[i] - s[j]))
    if t <= m:
      m = t
      
print(m)

Submission status: Time Limit Exceeded

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

ans = []
for i in range(N):
    if i < N-1:
        ans.append(A[i+1]-A[i])

ans.append(K-A[N-1])

fin = []
for i in itertools.combinations(ans,N-1):
    fin.append(sum(i))
print(min(fin))

Submission status: Time Limit Exceeded

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

ans = []
for i in range(N):
    if i < N-1:
        ans.append(A[i+1]-A[i])
ans.append(K-A[N-1])

c = list(itertools.combinations(ans,N-1))

a = []
for i in range(len(c)):
    a.append(sum(c[i]))
print(min(a))

Submission status: Time Limit Exceeded

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

distance = []
for i in range(N-1):
    distance.append(A[i+1] - A[i])
distance.append(K - A[-1] + A[0])

for i in range(N):
    if distance[i] == max(distance):
        start = i

ans = K - max(distance)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
a = list(map(int, input().split()))
aa = sorted(a,reverse=True)
ans = []

for i in range(n-1):
    if k-aa[i] + aa[i+1] >= max(a)-min(a):
        ans.append(max(a) - min(a))
        
    else:
        ans.append(k - aa[i] + aa[i+1])

print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int, input().split())
A = map(int, input().split())
dist = 0
for a in A:
    dist |= 1 << a
dist = format(dist, "0%db" % K)
d = dist.index("1")
ans = 0
count = 0
for i in range(K):
    if dist[(d + i) % K] == "1":
        ans = max(ans, count)
        count = 0
    else:
        count += 1
ans = max(ans, count)
print(K - ans - 1)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

ans = float('inf')
roots = list(itertools.permutations(a))

for i in range(n):
    sum_d = 0
    root = list(roots[i])
    for j in range(1, n):
        sum_d += min(abs(root[j] - root[j - 1]), abs(k - root[j] + root[j - 1]))
    if sum_d < ans:
        ans = sum_d
print(ans)

Submission status: Time Limit Exceeded

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

for i in range(n-1):
    for j in range(n-1-i):
        if A[j] > A[j+1]:
            A[j],A[j+1] = A[j+1],A[j]


max_d = 0
max_index = 0
for i in range(n-1):
    if A[i+1] - A[i] > max_d:
        max_d = A[i+1]-A[i]
        max_index = i

if k-A[n-1]+A[0] > max_d:
    max_d = k-A[n-1]+A[0]
    max_index = n-1

min_distance = 0

if(max_index != n-1):
    min_distance = A[max_index]+k-A[max_index+1]
else:
    min_distance = A[n-1]-A[0]

print(min_distance)

Submission status: Time Limit Exceeded

Solution code:
inp  = list(map(int, input().strip().split()))
array = list(map(int, input().strip().split()))

lis = []
for i in range(1, inp[1]):
    lis.insert(0, array[i] - inp[0])
lis.sort()
lis.extend(array)
# print(lis)

dif = []
for i in range(0, len(lis)-1):
    dif.append(lis[i+1]-lis[i])

l = inp[1]-1
for i in range(0, inp[1]):
    if i == 0:
        a = sum(dif[:l])
    else:
        b = sum(dif[i:i+l])
        if b < a:
            a = b
print(a)

Submission status: Time Limit Exceeded

Solution code:
inp  = list(map(int, input().strip().split()))
array = list(map(int, input().strip().split()))

ans = array.copy()
for i in range(1, inp[1]):
    ans.insert(0, array[i] - inp[0])
ans.sort()
# print(ans)
dif = []
for i in range(0, len(ans)-1):
    dif.append(ans[i+1]-ans[i])
# print(dif)


# print(dif)
l = inp[1]-1
for i in range(0, inp[1]):
    if i == 0:
    #     print(dif[:l])
        a = sum(dif[:l])
    else:
        # print(dif[i:i+l])
        b = sum(dif[i:i+l])
        if b < a:
            a = b
print(a)

Submission status: Time Limit Exceeded

Solution code:
K, N = [ int(i) for i in input().split()]

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

for i in range(0, N):
  distances = n
  if i > 0:
    distances[i-1] += K
    
  total.append(max(distances) - distances[i])
  
print(min(total))

Submission status: Time Limit Exceeded

Solution code:
K, N  = map(int,input().split())
List = list(map(int,input().split()))
d = []
for i in range(N):
  for j in range(N):
    x = min(abs(List[i]-List[j]), K-abs(List[i]-List[j]))
    d.append(x)
result = K - int(max(d))
print(result)

Submission status: Time Limit Exceeded

Solution code:
import math
K, N  = map(int,input().split())
List = list(map(int,input().split()))
d = []
for i in range(N):
  for j in range(N):
    x = min(abs(List[i]-List[j]), K-abs(List[i]-List[j]))
    d.append(x)
result = K - int(max(d))
print(result)

Submission status: Time Limit Exceeded

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

a.append(k + a[0])
each_dist = [(a[i] - a[i - 1]) for i in range(1, n + 1)]
ans = k
for i in range(n):
    all_dist = sum(each_dist[: i] + each_dist[i + 1: ])
    if all_dist < ans:
        ans = all_dist

print(ans)

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
a=list(map(int,input().split()))
for j in range(n-1):
	a.append(a[j]+k)
sum=[0]*n
for I in range(n):
	for i in range(n-1):
		sum[I]=sum[I]+a[I+i+1]-a[I+i]
print(min(sum))

Submission status: Time Limit Exceeded

Solution code:
K,N=map(int,input().split())
A=list(map(int,input().split()))
b=[]
for i in range(N):
  if A[i]==0:
    b.append(A[N-1])
  else:
    for j in range(i+1,N):
      b.append(K-(A[j]-A[i]))
    

print(min(b))

Submission status: Time Limit Exceeded

Solution code:
k,n =map(int,input().split())
a=list(map(int, input().split()))
s=0
for i in range(n):
	if a[i]==min(a):
		s=max(s,k-a[i-1]+a[i])
	else:
		s=max(s,abs(a[i-1]-a[i]))
print(k-s)

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
A = list(map(int,input().split()))
AbsA = []
for i in range(0,K):
    if i<(K-1):
        AbsA = AbsA + [abs(A[i+1]-A[i])]
    else:
        AbsA = AbsA + [A[0] + N -A[i]]
maxA = max(AbsA)
print(N-maxA)

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
l1=list(map(int,input().split()))
l2 = [x+k for x in l1]
l=l1+l2
ans=[]
for i in range(n):
    ans.append(max(l[i+1:i+n])-l[i] )
print (min(ans))

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
l1=list(map(int,input().split()))
l2 = [x+k for x in l1]
l=l1+l2
ans=[]
for i in range(n):
    tmpList=[x-l[i] for x in l[i+1:i+n]]
    ans.append(max(tmpList))
print (min(ans))

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
l1=list(map(int,input().split()))
l2 = [x+k for x in l1]
l=l1+l2
ans=[]
for i in range(n):
    tmpList=[]
    for j in range(n-1):
      tmpList.append(l[j+1+i]-l[i])
    ans.append(max(tmpList))
print (min(ans))

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
l1=list(map(int,input().split()))
l2 = [x+k for x in l1]
l=l1+l2
ans=0
for i in range(n):
    tmpSum=0
    for j in range(n-1):
        tmpSum=max(tmpSum,l[j+1+i]-l[i])
    if ans==0:
        ans=tmpSum
    else:
        ans=min(ans,tmpSum)
print (ans)

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int, input().split())
A = list(map(int, input().split()))
A += [i+K for i in A]
diff = [A[i+1] - A[i] for i in range(N*2-1)]

length = sum(A)

for i in range(len(diff) - N + 1):
    length = min(length, sum(diff[i:i+N-1]))
print(length)

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
a=list(map(int,input().split()))
m=0
for i in range(n):
    for j in range(i+1,n):
        l=min(a[j]-a[i],k-a[j]+a[i])
        m=max(m,l)
print(k-m)

Submission status: Time Limit Exceeded

Solution code:
k, n = map(int, input().split())
A = list(map(int, input().split()))
ans = [0]*n
B = [0]*n

for j in range(n):
    for i in range(n):
        B[i] = A[i] - A[j]
        if abs(B[i]) >= k/2:
            B[i] = abs(B[i]) - k
    B.sort()
    #print(B)
    ans[j] = B[n-1] - B[0]
print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
import statistics

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

for i in a:
  target = i
  tmp = [abs(j - target) if abs(j - target) < abs(j - (target + k)) else abs(j - (target + k)) for j in a]
  dist.append(sum(tmp))
print(min(dist))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import itertools

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

for list in itertools.permutations(range(n)):
    count = 0
    for i in range(n-1):
        t1 = a[list[i+1]] - a[list[i]]
        t2 = a[list[i+1]] + 20 - a[list[i]]
        if t1 > k/2:
            count += k - t1
        elif t1 > 0:
            count += t1
        elif t2 > k/2:
            count += k - t2
        else:
            count += t2
    ans.append(count)
print(min(ans))

Submission status: Time Limit Exceeded

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

result = 10000000
for i, v in enumerate(dist_list):
  offset = 1
  total = 0
  while offset < N:
    if total >= result:
      break
    now_pos = dist_list[((i + offset - 1) % N)]
    next_pos = dist_list[((i + offset) % N)]
    if next_pos < now_pos:
      next_pos += K
    total += next_pos - now_pos
    offset += 1

  if result > total:
    result = total

print(result)

Submission status: Time Limit Exceeded

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

result = 0
for i, v in enumerate(dist_list):
  offset = 1
  total = 0
  while offset < N:
    now_pos = dist_list[((i + offset - 1) % N)]
    next_pos = dist_list[((i + offset) % N)]
    if next_pos < now_pos:
      next_pos += K
    total += next_pos - now_pos
    offset += 1

  if (result == 0 or result > total):
    result = total

print(result)

Submission status: Time Limit Exceeded

Solution code:
k,n  = map(int,input().split())
diff = lambda x:x[1]-x[0]
a = list(map(int,input().split()))
distance = a+[a[0]+k]
diffs = [diff(distance[i:i+2]) for i in range(len(distance)-1)]
diffs = diffs + [diffs[i] for i in range(0,n-2)]
sums = [sum(diffs[i:i+n-1]) for i in range(len(diffs)-(n-2))]
print(min(sums))

Submission status: Time Limit Exceeded

Solution code:
k,n  = map(int,input().split())
diff = lambda x:x[1]-x[0]
sum_list = lambda x:sum(x)
a = list(map(int,input().split()))
distance = a+[a[0]+k]
diffs = [diff(distance[i:i+2]) for i in range(len(distance)-1)]
diffs = diffs + [diffs[i] for i in range(0,n-2)]
sums = [sum_list(diffs[i:i+n-1]) for i in range(len(diffs)-(n-2))]
print(min(sums))

Submission status: Time Limit Exceeded

Solution code:
distance,num = map(int, input().split())
tmp = input()
a = tmp.split()
a = list(map(int,a))
b = []

for i in range(len(a)-1):
    b.append(a[i+1] - a[i])
b.append(distance - a[i+1] + a[0])

total = 0
min = 10000000000
for i in range(num):
    total = b[i]
    j = i + 1
    if i == 0:
        end = num - 1
    else:
        end = i - 1
    while(j != end):
        if j == num:
            j = 0
        else:
            total += b[j]
            j += 1
    if min > total:
        min = total

for i in range(num):
    total = b[i]
    j = i - 1
    if i == num - 1:
        end = 0
    else:
        end = i + 1
    while(j != end):
        if j == -1:
            j = num - 1
        else:
            total += b[j]
            j -= 1
    if min > total:
        min = total

print(min)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

dist_home=[A[x+1]-A[x] for x in range(N-1)]
dist_home.append(K-A[N-1]+A[0])

print(min(map(lambda x: sum(x), itertools.combinations(dist_home,N-1))))

Submission status: Time Limit Exceeded

Solution code:
import itertools

s=[]
while True:
  try:
    s.append(list(map(int,input().split())))
  except:
    break

K=s[0][0]
N=s[0][1]
A=s[1]

dist_home=[A[x+1]-A[x] for x in range(N-1)]
dist_home.append(K-A[N-1]+A[0])

print(min(map(lambda x: sum(x), itertools.combinations(dist_home,N-1))))

Submission status: Time Limit Exceeded

Solution code:
import itertools

s=[]
while True:
  try:
    s.append(input().split())
  except:
    break
s=[int(x) for y in s for x in y]

K=s[0]
N=s[1]
A=s[2:]

dist_home=[]
for i in range(N):
  if i+1<N:
    dist_home.append(A[i+1]-A[i])
  else:
    dist_home.append(K-A[i]+A[0])

print(min(map(lambda x: sum(x), itertools.combinations(dist_home,N-1))))

Submission status: Time Limit Exceeded

Solution code:
import itertools

s=[]
while True:
  try:
    s.append(list(map(int,input().split())))
  except:
    break

K=s[0][0]
N=s[0][1]
A=s[1]

dist_home=[]
for i in range(N):
  if i+1<N:
    dist_home.append(A[i+1]-A[i])
  else:
    dist_home.append(K-A[i]+A[0])

print(min(map(lambda x: sum(x), itertools.combinations(dist_home,N-1))))

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):
    for j in range(N):
        C=abs(A[i]-A[j])
        D=K-C
        if C>D:
            saidai=D
        else:
            saidai=C
        if ans<saidai:
            ans=saidai
        else:
            pass
print(ans)

Submission status: Time Limit Exceeded

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

answer = [0] * kn[1]

for j in range(kn[1]):
    for i in range(kn[1]-1):
        if i+j != kn[1]-1:
            answer[j] += A[(i+j+1)%3] - A[(i+j)%3]
        else:
            answer[j] += kn[0] - A[-1] + A[0]
print(min(answer))

Submission status: Time Limit Exceeded

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

answer = [0] * kn[1]

for j in range(kn[1]):
    for i in range(kn[1]-1):
        if i+j != kn[1]-1:
            answer[j] = answer[j] + A[(i+j+1)%3] - A[(i+j)%3]
        else:
            answer[j] = answer[j] + kn[0] - A[-1] + A[0]
print(min(answer))

Submission status: Time Limit Exceeded

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

cal_A = A
cal_A.append(K)
dis_A = []
ans_raw = []

for i in range(0, N):
    a = cal_A[i+1] - cal_A[i]
    dis_A.append(a)

for i in range(0, N):
    a = sum(dis_A) - dis_A[i]
    ans_raw.append(a)

print(str(min(ans_raw)))

Submission status: Time Limit Exceeded

Solution code:
data1 = input()
data2 = input()
circle = int(data1.split()[0])

dist = [int(s) for s in data2.split()]
d = []
for base in dist:
  m = 0
  for e in dist:
    if e != base:
      m += min(abs(e-base),circle-abs(e-base))
  d.append(m)
print(min(d))