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 = map(int, input().split())
a = list(map(int, input().split()))
d = [a[0]]

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

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]
    if normal_ck > reverse_ck:
        min_ck = reverse_ck
    else:
        min_ck = normal_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 = list(map(int, input().split()))
A = list(map(int, input().split()))

if A[0] != 0:
    B = A + [K] 
else:
    B = A
#print(B)

for i in range(N):
    B.append(A[i] + K)
#print(B)

C =[]
for i in range(N):
    cnt = 0
    for j in range(i, i + N - 1):
        cnt +=B[j+1] -B[j]
    C.append(cnt)

print(min(C))

Submission status: Time Limit Exceeded

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

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

mn = 0
Amax = max(An)
Amin = min(An)
for i in range(len(An)):
    cal = 0
    A = An[i:]  + An[:i]
    for i in range(len(A)-1):
        if A[i] == Amax and A[i+1] == Amin:
            cal += A[i+1] + k - A[i]
        elif A[i] == Amin and A[i+1] == Amax:
            cal += A[i] + k - A[i+1]
        elif A[i+1] >= A[i]:
            cal += A[i+1] - A[i]
        else:
            cal += A[i] - A[i+1]
        
        if mn > 0 and cal > mn:
            break
    
    if mn ==0 or mn > cal:
        mn = cal
        
rAn = An[:]
rAn.reverse()
for i in range(len(rAn)):
    cal = 0
    A = rAn[i:]  + rAn[:i]
    for i in range(len(A)-1):
        if A[i] == Amax and A[i+1] == Amin:
            cal += A[i+1] + k - A[i]
        elif A[i] == Amin and A[i+1] == Amax:
            cal += A[i] + k - A[i+1]
        elif A[i+1] >= A[i]:
            cal += A[i+1] - A[i]
        else:
            cal += A[i] - A[i+1]
            
        if mn > 0 and cal > mn:
            break

    if mn ==0 or mn > cal:
        mn = cal
print(mn)

Submission status: Time Limit Exceeded

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

box = []
for i in range(N):
    a = abs(A[i-1]-A[i])
    if a>K/2:
        a = K - a
    box.append(a)
box.extend(box)
dis = []
for i in range(N):
    d = sum(box[i:i+N-1])
    dis.append(d)

print(min(dis))

Submission status: Time Limit Exceeded

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

A_list = list(itertools.permutations(A, N))
ans = 10**8
for i in A_list:
    tmp = 0
    
    if (i[0] == min(A) and i[2] == max(A)) or  (i[0] == max(A) and i[2] == min(A)):
        for j in range(N-1):
            if abs((i[j+1]) - (i[j])) <= abs(K-i[j+1]):
                tmp = tmp +  abs((i[j+1]) - (i[j]))
            else:
                tmp = tmp + abs(K-i[j+1])
        
        if tmp <= ans:
            ans = tmp
    else:
        pass
print(ans)

Submission status: Time Limit Exceeded

Solution code:
k, n = map(int, input().split())
a_list = input().split()  # sはlist

dis_list = []
for a in a_list:
    for b in a_list:
        dis=max(int(a)-int(b),int(b)-int(a))
        dis_list.append(min(dis,k-dis))
print(max(dis_list))

Submission status: Time Limit Exceeded

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

a = []
a = 1000000
for i in range(len(lists)):
    if abs(K - lists[i]) == 0:
        continue
    elif abs(K - lists[i]) < a:
        a = abs(K - lists[i])
b = 1000000
for i in range(len(lists)):
    for j in range(len(lists)):
        if abs(lists[i] - lists[j]) == 0:
            continue
        elif abs(lists[i] - lists[j]) < b:
            b = abs(lists[i] - lists[j])

# print(a)
# print(b)
c = a+b
print(c)

Submission status: Time Limit Exceeded

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

# 距離間リスト
d_li = []
for i in range(N-1):
	d_li.append(A_li[i+1]-A_li[i])

d_li.append(K+A_li[0] - A_li[N-1])

ans = float('inf')
for d in d_li:
	ans = min(ans,sum(d_li)-d)

print(ans)

Submission status: Time Limit Exceeded

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

k2 = k // 2
bet = [210000] * (n - 1) + [0] * 1
for i in range(n):
    for j in range(n):
        if i != j:
            if (0 <= a[i] < 10) and (10 < a[j] < 20):
                bet[i] = min(bet[i], abs(a[i]) - (a[j] - k))
            elif (0 <= a[j] < 10) and (10 < a[i] < 20):
                bet[i] = min(bet[i], abs(a[j]) - (a[i] - k))
            else:
                bet[i] = min(bet[i], abs(a[i] - a[j]))
#print(bet)
print(sum(bet))

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int, input().split())
A = list(map(int, input().split()))
max_dis = 0
for i in range(N - 1):
    for j in range(i+1, N):
            tmp = A[j] - A[i]
            if tmp > K // 2:
                tmp -= K//2
            max_dis = max(max_dis, tmp)

print(K - max_dis)

Submission status: Time Limit Exceeded

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

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

mn = 0
Amax = max(An)
Amin = min(An)
for i in range(len(An)):
    cal = 0
    A = An[i:]  + An[:i]
    for i in range(len(A)-1):
        if A[i] == Amax and A[i+1] == Amin:
            cal += A[i+1] + k - A[i]
        elif A[i] == Amin and A[i+1] == Amax:
            cal += A[i] + k - A[i+1]
        elif A[i+1] >= A[i]:
            cal += A[i+1] - A[i]
        else:
            cal += A[i] - A[i+1]
    if mn ==0 or mn > cal:
        mn = cal

rAn = An[:]
rAn.reverse()
for i in range(len(rAn)):
    cal = 0
    A = rAn[i:]  + rAn[:i]
    for i in range(len(A)-1):
        if A[i] == Amax and A[i+1] == Amin:
            cal += A[i+1] + k - A[i]
        elif A[i] == Amin and A[i+1] == Amax:
            cal += A[i] + k - A[i+1]
        elif A[i+1] >= A[i]:
            cal += A[i+1] - A[i]
        else:
            cal += A[i] - A[i+1]
    if mn ==0 or mn > cal:
        mn = cal
print(mn)

Submission status: Time Limit Exceeded

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

A_list = list(itertools.permutations(A, N))
ans = 10**8
for i in A_list:
    tmp = 0
    
    if i[0] == min(A) and i[2] == max(A):
        pass
    else:
        for j in range(N-1):
            if abs((i[j+1]) - (i[j])) <= abs(K-i[j+1]):
                tmp = tmp +  abs((i[j+1]) - (i[j]))
            else:
                tmp = tmp + abs(K-i[j+1])
        
        if tmp <= ans:
            ans = tmp
print(ans)

Submission status: Time Limit Exceeded

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

ans = 10 ** 12
for i in range(N):
  d = 0
  for j in range(N):
    a = abs(A[i]-A[j])
    d += min(a, K-a)
  ans = min(ans, d)
print (ans)

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import itertools

k, n = map(int, input().split())
a = tuple(map(int, input().split()))
ans = 100000000000000000000

dist = []
pattern = sorted(list(itertools.permutations(a)))
#print(pattern)
#print(len(pattern))

for i in range(len(pattern)):
    tmp = 0
    for j in range(0,n-1):
        right = abs(pattern[i][j+1] - pattern[i][j])
        left = abs(k - pattern[i][j+1])
        #print(right, left)
        tmp += min(right, left)
    if tmp < ans:
        ans = tmp

#print(dist)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
k,n = map(int, input().split())
a = list(map(int, input().split()))
#print(k,n,a)
dist = 0
for i in range(n):
  for j in range(i, n):
    if a[j] - a[i] >= k//2:
      dist_x = k - (a[j] - a[i]) 
    else:
      dist_x = a[j]-a[i]
  if dist < dist_x:
    dist = dist_x
print(dist)

Submission status: Time Limit Exceeded

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

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

min_distance = -1
for i in range(len(a_list)):
    total_distance = 0
    
    total_distance = 0
    for j in range(len(a_list)):
        if i == j:
            continue
        else:
            distance1 = abs(a_list[i] - a_list[j])
            distance2 = abs(a_list[i] - a_list[j] + 20)
            total_distance += min(distance1, distance2)
   
    if min_distance > total_distance:
        min_distance = total_distance
    elif min_distance == -1:
        min_distance = total_distance
        
print(min_distance)

Submission status: Time Limit Exceeded

Solution code:
input_line = [int(i) for i in input().split()]
k = input_line[0]
n = input_line[1]
input_line = [int(i) for i in input().split()]
rev = [k - i for i in input_line]
houses = rev + [0] + input_line
abs_houses = []
for i in range(n * 2):
  abs_houses.append(abs(houses[i] - houses[i + 1]))
abs_houses = abs_houses[0:n-1] + [sum(abs_houses[n-1:n+1])] + abs_houses[n+1:n*2]
distances = []
for i in range(n):
  distances.append(sum(abs_houses[i : i + n - 1]))
print(min(distances))

Submission status: Time Limit Exceeded

Solution code:
import copy

K,N = map(int, input().split())
An = list(map(int, input().split()))
ans = [max(An) - min(An)]
for i in range(int(len(An)/2),len(An)):
    A_list = copy.copy(An)
    A_list[i] = A_list[i]-K
    ans.append(max(A_list) - min(A_list))
print(min(ans))

Submission status: Time Limit Exceeded

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

a_list_ = input().split()  # sはlist
a_list = [int(x) for x in a_list_]

dis_list = []
for a in a_list:
    for b in a_list:
        dis=max(a-b,b-a)
        dis_list.append(min(dis,k-dis))
print(max(dis_list))

Submission status: Time Limit Exceeded

Solution code:
k,n=[int(i) for i in input().split()]
A=[int(i) for i in input().split()]
m=100000
for i in range(len(A)):
    x=A[i]
    a=A[:i]+A[i+1:]
    s=0
    for j in range(len(a)):
        s+=min(abs(a[j]-x),k-a[j]+x)
    if m>s:
        m=s
print(m)

Submission status: Time Limit Exceeded

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

dis = 0

a = A[0]
for i in range(len(A)-1):
    min_d = 1e6
    for i in range(1,len(A)-1):
        if a>A[i]:
            d = min(abs(a-A[i]), abs(a-A[i]-20))
        else:
            d = min(abs(a-A[i]), abs(a-A[i]+20))
        min_d = min(d, min_d)
    dis += min_d
print(dis)

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import itertools

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

dist = []
pattern = sorted(list(itertools.permutations(a)))
#print(pattern)
#print(len(pattern))

for i in range(len(pattern)):
    tmp = 0
    for j in range(0,n-1):
        right = abs(pattern[i][j+1] - pattern[i][j])
        left = abs(k - pattern[i][j+1])
        #print(right, left)
        tmp += min(right, left)
    dist.append(tmp)

#print(dist)
print(min(dist))

Submission status: Time Limit Exceeded

Solution code:
k,n=map(int,input().split())
home = input()
home = home.split()
for i in range(len(home)):
    home[i] = int(home[i])

def search(i,home,l):
    d = 0
    leng = len(home)
    count=0
    while True:
        if count==leng-1:
            break
        j=i+1
        if j==leng:
            d+=home[0]+k-home[i]
            count+=1
            continue
        d += home[i+1]-home[i]
        count+=1
        i+=1
        if i == leng:
            i=0
    d2=0
    while True:
        if count==leng-1:
            break
        j=i-1
        if j==-1:
            d2+=home[leng-1]-home[0]+k
            count+=1
            continue
        d2 += home[i-1]-home[i]
        count+=1
        i+=1
        if i == -1:
            i=leng-1
    if d<=d2:
        l.append(d2)
    else:
        l.append(d)
    return
        


l=[]
for i in range(len(home)):
    search(i,home,l)
print(min(l))

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy

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

a = list(map(int, input().split()))
a_ = deepcopy(a)
ans = 1000000
for index in range(len(a)):
    temp = max(a) - min(a)
    a[index] = a[index] + k
    if ans > temp:
        ans = temp

for index in reversed(range(len(a))):
    # print(a_, temp, max(a_), min(a_))
    temp = (max(a_) - min(a_))
    # print(temp)
    a_[index] -= k
    if ans > temp:
        ans = temp

print(ans)

Submission status: Time Limit Exceeded

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

next_ls = [0] * n
for i in range(n-1):
    next_ls[i] = a_ls[i+1] - a_ls[i]
next_ls[n-1] = k - a_ls[-1] + a_ls[0]
next_ls = next_ls * 2

dist = float('inf')
for i in range(n):
    costs = next_ls[i:i+n-1]
    sum_ = sum(costs)
    if sum_ < dist:
        dist = sum_

print(dist)

Submission status: Time Limit Exceeded

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

a_list_ = input().split()  # sはlist
a_list = [int(x) for x in a_list_]

dis_list = []
for a in a_list:
    for b in a_list:
        dis_list.append(min(max(a-b,b-a),k-max(a-b,b-a)))
print(max(dis_list))

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations

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

res = 0

ans = 10 ** 10
for i in range(N):
    t0 = A[0]
    A.remove(t0)
    A.append(t0)
#    print(A)
    for j in range(N-1):
        if(A[j] == 0):
            res += 0
        else:
            res += abs(A[j] - A[j+1])
    if(ans > res):
        ans = res
    res = 0

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):
  A.append(A[i]+K)
d = 0; ans = float("INF")
for i in range(N):
  d = 0
  for j in range(N-1):
    d += A[i+j+1] - A[i+j]
  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()))

# tmp1 = A[-1] - A[0]
# tmp2 = A[-1] - (20 - A[0] - A[-1])
# tmp2 = A[-1] - A[1]

# print(min(tmp1, tmp2))
# # print(A[-1]-A[0])

# ans = []
ans = -1
for i in range(N):
    tmp = 0
    I = A[i]
    for j in range(N-1):
        index = i + j + 1
        if index >= N:
            index -= N
        J = A[index]
        if I < J:
            tmp += J - I
        else:
            tmp += K - I + J
        # print(I,J, tmp)
        I = J
    if ans == -1:
        ans = tmp
    elif ans > tmp:
        ans = tmp
    # ans.append(tmp)
print(ans)
# print(ans)
# print(min(ans))

Submission status: Time Limit Exceeded

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

d=[]
for i in range(len(a)-1):
    d.append(abs(a[i]-a[i+1]))

d.append(k-a[-1]+a[0])
d+=d[:n-2]
ans=[]
for i in range(n):
    total=sum(d[i:i+n-1])
    ans.append(total)

print(min(ans))

Submission status: Time Limit Exceeded

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


ans = K
for x in range(N):
    i_x = i[x]
    list_i = list(map(lambda z: (z - i_x)%K , i))
    if (max(list_i)-min(list_i)) < ans:
        ans = max(list_i)-min(list_i)
print(ans)

Submission status: Time Limit Exceeded

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

m  = k
for i in range(n):
    b = a[i::] + a[0:i]
    r = 0
    for j in range(n-1):
        #print(r, b[j+1], b[j])
        if b[j] > b[j+1]:
            r = r + b[j+1] + (k - b[j])
        else:
            r = r + b[j+1] - b[j]
    m = min(m, r)
    #print(m,"kkkkk")
    
d = a[::-1]
for i in range(n):
    b = d[i::] + d[0:i]
    r = 0
    for j in range(n-1):
        #print(r, b[j+1], b[j])
        if b[j] > b[j+1]:
            r = r + b[j+1] + (k - b[j])
        else:
            r = r + b[j+1] - b[j]
    m = min(m, r)
print(m)

Submission status: Time Limit Exceeded

Solution code:
input_line = input().split(' ')
input_list = [int(i) for i in input_line]
k = input_list[0]
n = input_list[1]

listA = input().split(' ')
listA = [int(a) for a in listA]
distance = []

for start in listA:
    pos = start
    frag = 0
    dis = 0
    for i in range(2):
        if i == 0:
            while frag < 2:
                pos += 1
                dis += 1
                if pos >= k:
                    pos = 0
                if pos in listA:
                    frag += 1
        else:
            while frag < 2:
                pos -= 1
                dis += 1
                if pos <= 0:
                    pos = k
                if pos in listA:
                    frag += 1
        distance.append(dis)

print(min(distance))

Submission status: Time Limit Exceeded

Solution code:
K, N = list(map(int,input().split()))
A = list(map(int,input().split()))
for i in range(len(A)):
    min_this = 0
    for j in range(len(A)-1):
        now_point = A[i+j-len(A)]
        next_point = A[i+j+1-len(A)]
        if next_point - now_point < 0:
            min_this += (K-now_point) + next_point
        else:
            min_this += next_point - now_point
    if i==0:
        total_min = min_this
    else:
        if min_this < total_min:
            total_min = min_this
print(total_min)

Submission status: Time Limit Exceeded

Solution code:
import sys
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)

K, N = map(int, readline().split())
A = list(map(int, readline().split()))
A_ = [a + K for a in A]

ans = 10**9 + 7
min1, max1 = min(A), max(A)

for i, a_ in enumerate(A_):
    A_[i] -= K
    max2 = max(A_)
    min2 = min(A_)
    acc = min(max1 - min1, max2 - min2)
    ans = min(ans, acc)
    A_[i] += K

print(ans)

Submission status: Time Limit Exceeded

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

# tmp1 = A[-1] - A[0]
# tmp2 = A[-1] - (20 - A[0] - A[-1])
# tmp2 = A[-1] - A[1]

# print(min(tmp1, tmp2))
# # print(A[-1]-A[0])

ans = []
for i in range(N):
    tmp = 0
    I = A[i]
    for j in range(N-1):
        index = i + j + 1
        if index >= N:
            index -= N
        J = A[index]
        if I < J:
            tmp += J - I
        else:
            tmp += K - I + J
        # print(I,J, tmp)
        I = J
    ans.append(tmp)

# print(ans)
print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
k, n = map(int, input().split())
a = list(map(int, input().split()))
ans = []
ans.append(max(a) - min(a))
for i in range(n):
    if a[i] > k // 2:
        a[i] = (k - a[i]) * -1
    ans.append(max(a) - min(a)) 
print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
input_line = input().split(' ')
input_list = [int(i) for i in input_line]
k = input_list[0]
n = input_list[1]

listA = input().split(' ')
listA = [int(a) for a in listA]
distance = []

for start in listA:
    pos = start
    frag = 0
    dis = 0
    for i in range(2):
        if i == 0:
            while frag < 3:
                if pos in listA:
                    frag += 1
                pos += 1
                dis += 1
                if pos >= k:
                    pos = 0
        else:
            while frag < 3:
                if pos in listA:
                    frag += 1
                pos -= 1
                dis += 1
                if pos <= 0:
                    pos = k
        distance.append(dis)

print(min(distance)-1)

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int, input().split())
houses = list(map(int, input().split()))
# syaku_houses = []
# for i, num in enumerate(houses):
#     if i == 0:
#         syaku_houses.append(num)
#     else:
#         syaku_houses.append(num - houses[i - 1])
# print(syaku_houses)

# min_costs = []
# for house in syaku_houses:

# 右回りか左回りか？
reverse_houses = []
for i in range(N - 1):
    reverse_houses.insert(0, -1 * (K - houses[N - 1 - i]))
reverse_houses.reverse()
for house in reverse_houses:
    houses.insert(0, house)

min_costs = []
for i in range(N):
    min_costs.append(houses[N - 1 + i] - houses[i])
print(min(min_costs))

Submission status: Time Limit Exceeded

Solution code:
t,n=map(int,input().split())
x=list(map(int,input().split()))
xx=[i+t for i in x]
x=x+xx
dis=[]
for i in range(2*n-1):
    dis.append(x[i+1]-x[i])

ans=[]
for j in range(2*n-2):
    ans2=dis[j:j+n-1]
    ans.append(sum(ans2))
print(min(ans))

Submission status: Time Limit Exceeded

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

dis = 0

n = len(A)
idx = 0
a = A[0]
while n>1:
    min_idx = 0
    min_d = 1e6
    for i in range(len(A)):
        if not idx == i:
            if a>A[i]:
                d = min(abs(a-A[i]), abs(a-A[i]-20))
            else:
                d = min(abs(a-A[i]), abs(a-A[i]+20))
            if d<min_d:
                min_d = d
                min_idx = i
    a = A[i]
    idx = i
    dis += min_d
    n-=1
print(dis)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

A.append(K + A[0])

diff = np.diff(A).tolist()

min_ = sum(diff)
for i in range(len(diff)):
  diff_ = diff[:]
  diff_.remove(diff[i])
  if min_ > sum(diff_):
    min_ = sum(diff_)

print(min_)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline

from decimal import *

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

##### 累乗 #####
# pow(x, y, z) -> x**y % z

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

inf = float('inf')
mod = 1000000007

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

def main():
	K,N = inputMap()
	A = inputList()

	ans = inf
	for j,vol in enumerate(A):
		tmp = vol
		tmpA = A[j:]
		taisl = K - A[-1]
		#print()
		for ii in A[:j]:
			tmpA.append(taisl + A[-1] +  ii)
		tmpans = 0
		#print(tmpA)
		for i,vol in enumerate(tmpA):
			if i == 0:
				tt = vol
				continue
			tmpans += vol - tt
			tt = vol
		#print(tmpans)
		if ans > tmpans:
			ans = tmpans

	print(ans)


#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# special thanks :
#  https://nagiss.hateblo.jp/entry/2019/07/01/185421
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
def int_sqrt2(n):
    def f(prev):
        while True:
            m = (prev + n / prev) / 2
            if m >= prev:
                return prev
            prev = m

    return f(int(math.sqrt(n) * (1 + 1e-10)))

# nCr mod m
# rがn/2に近いと非常に重くなる
def combination(n, r, mod=10**9+7):
    r = min(r, n-r)
    res = 1
    for i in range(r):
        res = res * (n - i) * modinv(i+1, mod) % mod
    return res

# mを法とするaの乗法的逆元
def modinv(a, mod=10**9+7):
    return pow(a, mod-2, mod)

def egcd(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, y, x = egcd(b % a, a)
        return g, x - (b // a) * y, y

# nHr mod m
# 問題によって、combination()を切り替えること
def H(n, r, mod=10**9+7):
	# comb = Combination(n+r-1, mod)
	# return comb(n+r-1, r)
    return combination(n+r-1, r, mod)

class Combination:
    """
    O(n)の前計算を1回行うことで，O(1)でnCr mod mを求められる
    n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
    使用例：
    comb = Combination(1000000)
    print(comb(5, 3))  # 10
    """
    def __init__(self, n_max, mod=10**9+7):
        self.mod = mod
        self.modinv = self.make_modinv_list(n_max)
        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def make_factorial_list(self, n):
        # 階乗のリストと階乗のmod逆元のリストを返す O(n)
        # self.make_modinv_list()が先に実行されている必要がある
        fac = [1]
        facinv = [1]
        for i in range(1, n+1):
            fac.append(fac[i-1] * i % self.mod)
            facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
        return fac, facinv

    def make_modinv_list(self, n):
        # 0からnまでのmod逆元のリストを返す O(n)
        modinv = [0] * (n+1)
        modinv[1] = 1
        for i in range(2, n+1):
            modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
        return modinv

if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

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

a += [k]
x = [a[i+1]-a[i] for i in range(n)]


answer = sum(x)
for i in range(n):
    _x = x[:i] + x[i+1:]
    answer = min(answer, sum(_x))
print(answer)

Submission status: Time Limit Exceeded

Solution code:
K, N = map(int, input().split())
lis = list(map(int, input().split()))
dis=[]
for _ in range(N):
  p = lis.pop(0)
  lis.append(p)
  d = 0
  for i in range(N-1):
    if lis[i+1] > lis[i]:
      d += (lis[i+1]-lis[i])
    else:
      d += (K - lis[i]) + lis[i+1]
  dis.append(d)
print(min(dis))

Submission status: Time Limit Exceeded

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

MAX = 0
for i in range(len(A)-1):
    for j in range(i+1,len(A)):
        d = abs(A[j]-A[i])
        MAX = max(MAX,d)
print(abs(sum(A)-MAX*(len(A)-1)))

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

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

res = 0
tmp = permutations(A,N)

ans = 10 ** 10
for i in tmp:
    for j in range(N-1):
        if(i[j] == 0):
            res += 0
        else:
            res += abs(i[j] - i[j+1])
    #print(res)
    #print(ans)
    if(ans > res):
        ans = res

print(ans)

Submission status: Time Limit Exceeded

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

mn=999
for v in itertools.permutations(A,N):
    t=0
    for i in range(1,len(v)):
        t+=min(abs(v[i]-v[i-1]), abs(v[i]-K-v[i-1]))    
    mn=min(t,mn)
print(mn)

Submission status: Time Limit Exceeded

Solution code:
import copy

K,N = map(int, input().split())
An = list(map(int, input().split()))
ans = [max(An) - min(An)]
for i in range(len(An)):
    A_list = copy.copy(An)
    A_list[i] = A_list[i]-K
    ans.append(max(A_list) - min(A_list))
print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

ans = K
for x in range(N):
    i_x = i[x]
    list_i = list((np.array(i)-i_x)%K)
    if (max(list_i)-min(list_i)) < ans:
        ans = max(list_i)-min(list_i)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
k, n = map(int, input().split())
h = [int(x) for x in input().split()]
sum = sum(h) // n
near = k
for x in h:
    if 0<sum-x < k:
        near = x
nearh = k
res = 0
h.remove(near)
while h != []:
    for x in h:
        if 0< near -x < nearh:
            res += near -x
            near = x
            h.remove(x)
        elif 0<x - near < nearh:
            res += x - near
            near = x
            h.remove(x)
        if near == 0: near = k
print(res)

Submission status: Time Limit Exceeded

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
# from fractions import gcd
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from functools import reduce
from bisect import bisect_left, insort_left
from heapq import heapify, heappush, heappop

INPUT = lambda: sys.stdin.readline().rstrip()
INT = lambda: int(INPUT())
MAP = lambda: map(int, INPUT().split())
S_MAP = lambda: map(str, INPUT().split())
LIST = lambda: list(map(int, INPUT().split()))
S_LIST = lambda: list(map(str, INPUT().split()))
ZIP = lambda: zip(*(MAP() for _ in range(n)))

sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7


def main():
    K, N = MAP()
    A = LIST()

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

    ans = INF
    for i in range(N-1):
        ans = min(ans, sum(lis[i:i+N-1]))
        
    ans = min(ans, sum(lis[N-1:]) + lis[0])
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
k, n = [int(elem) for elem in input().split()]
a_lst = [int(elem) for elem in input().split()]

diff = []
for i, a in enumerate(a_lst[:-1]):
    diff.append(a_lst[i+1] - a)
diff.append((a_lst[0] + k) - a_lst[-1])

res = []
for j in range(len(diff)):
    res.append(sum(diff) - diff[j])
print(min(res))

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

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

res = 0
tmp = permutations(A,N)

ans = 10 ** 10
for i in tmp:
    for j in range(N-1):
        if(A[j] == 0):
            res += 0
        else:
            res += abs(A[j] - A[j+1])
    if(ans > res):
        ans = res
print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
K,N=map(int,input().split())
#print(K,N)
A=list(map(int,input().split()))
#print(A)
#print(A[1:N])
#print(A[0:(N-1)])

D0 = 0
for i in range(N-1):
    D = A[1:N][i] - A[0:(N-1)][i]
    if D > D0:
        D0 = D
z = K - A[N-1] + A[0]
if z > D0:
    D0 = z
print(K - D0)