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 .

Solution (Python):
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


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


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


def print_matrix(mat):
    for i in range(len(mat)):
        print(*mat[i])


yn = {False: 'No', True: 'Yes'}
YN = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False



def main():
    K, N = MI()
    A = LI()
    A.append(A[-1] + (K - A[-1]) + A[0])
    N = N + 1
    diff_sum = 0
    diff = -1
    target = -1

    for i in range(N-1):
        v = abs(A[i] - A[i+1])
        diff_sum += v

        if diff < v:
            diff = v
            target = i

    
    print(diff_sum - diff)

    
    
    
    

    
    
    

    
    
    
    

    
    
    

    
    


if __name__ == '__main__':
    main()

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

maxdis = 0
for i in range(len(A)-1):
  if maxdis < A[i+1] - A[i]:
    maxdis = A[i+1] - A[i]
if maxdis < (K - A[-1]) + A[0]:
  maxdis = (K - A[-1]) + A[0]
print(K-maxdis)

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

Solution (Python):
import numpy as np
K, N = map(int,input().split())
As = list(map(int, input().split()))
As = np.array(As)
Bs = np.copy(As)
As = np.append(As, 0)
Bs = np.append(0, Bs)
Cs = As-Bs
Cs = np.delete(Cs, 0, 0)
Cs = np.delete(Cs, -1, 0)
Cs = np.append(Cs, As[0]+K-As[-2])
idx = np.argmax(Cs)
print(K-Cs[idx])

Solution (Python):
import numpy as np
N,K = list(map(int, input().split()))
A = list(map(int, input().split()))
A_diff = np.diff(A)
A_diff_sum = np.sum(A_diff)
max_diff = np.max([np.max(A_diff), (N - A[-1] + A[0])])
ans = A_diff_sum - max_diff + (N - A[-1] + A[0])
print(ans)

Solution (Python):
x = input().split()
K = int(x[0])
N = int(x[1])
A = input().split()
A = [int(x) for x in A]

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

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

List = [int(i) for i in input().split()]
dis =[0] *N
for j in range(N):
  if j == N-1:
    dis[j]=K-List[j]+List[0]
  else:
    dis[j] = List[j+1]-List[j]
ans = sum(dis)-max(dis)

print(ans)

Solution (Python):
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()
diff = sorted(diff)

print(sum(diff[:-1]))

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

a.append(a[0] + k)
x = k - a[-2]
a.insert(0, x)

li = []
for i in range(1, n+1):
    d = min(k - abs(a[i]-a[i-1]), k - abs(a[i]-a[i+1]))
    li.append(d)

ans = min(li)
print(ans)

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

mini = K
right = left = K
for i in range(N):
	l_begin = i-1
	r_begin = i+1
	if i == 0:
		l_begin = N-1
		right = A[l_begin] - A[i]
		left = K - (A[r_begin]-A[i])
	elif i == N-1:
		r_begin = 0
		right = K - (A[i]-A[l_begin])
		left = A[i] - A[r_begin]
	else:
		right = K - (A[i]-A[l_begin])
		left = K - (A[r_begin]-A[i])
	local = min(right, left)
	if local < mini:
		mini = local
		

print(mini)

Solution (Python):
K,N=map(int,input().split())
list_a=list(map(int,input().split()))
x = K-list_a[N-1]+list_a[0]
p=0
for i in range(N-1):
    if list_a[1+i]-list_a[i]>p:
            p=list_a[1+i]-list_a[i]
if x>p:
    print(K-x)
else:
    print(K-p)

Solution (Python):
K, N = map(int, input().split())
A = list(map(int, input().split()))
Asa = 0

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

if Asa <= ((K - A[N -1]) + A[0]):
        Asa = (K - A[N -1]) + A[0]

print(K - Asa)

Solution (Python):
K,N=map(int,input().split())
A=list(map(int,input().split()))
B=0
for i in range(N-1):
    b=A[i+1]-A[i]
    if b>B:
        B=b
        n=i
b=K-A[N-1]+A[0]
if b>B:
    B=b
print(K-B)

Solution (Python):

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 *

























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

	toto = 0
	tmp = 0
	for j,vol in enumerate(A):
		if j == 0:
			tmp = vol
			continue
		toto += vol - tmp
		tmp = vol

	ans = toto
	toto = toto + (K - A[-1]) + A[0]

	A.append(K - A[-1] + A[0])

	for j,vol in enumerate(A):
		if j == 0:
			continue

		tmpans = toto - (vol - A[j-1])

		if ans > tmpans:
			ans = tmpans

	print(ans)







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



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


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



def H(n, r, mod=10**9+7):
	
	
    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))  
    """
    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):
        
        
        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):
        
        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()

Solution (Python):
k, n = [int(i) for i in input().split(" ")]
a = [int(i) for i in input().split(" ")]

d = min(k - (a[0] - (a[-1] - k)), k - (a[1] - a[0]))
for i in range(1, n-1, 1):
  d = min(d, k - (a[i]-a[i-1]), k - (a[i+1]-a[i]) )
print(d)

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

d_min = K
for i in range(N):
    start = A[i]
    if i + 1 < N:
        end = A[i + 1]
    else:
        end = A[0]
    rest = min(abs(start - end), K - abs(start - end))
    d = K - rest
    d_min = min(d_min, d)

print(d_min)

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

diff = []

for i in range(1, len(A)):
  diff.append(A[i] - A[i-1])
  
diff.append(K + A[0] - A[-1])

diff.remove(max(diff))

print(sum(diff))

Solution (Python):
import numpy as np

def main():
    k, n = map(int,input().split())
    a = list(map(int, input().split()))
    a.append(k+a[0])
    
    
    a2 = []
    for i in range(len(a)-1):
        a2.append(a[i+1]-a[i])
    a2 = np.array(a2)
    print(k-np.max(a2))
    
if __name__ == '__main__':
    main()

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

a.sort()
b = list()
for i in range(N-1):
    x = a[i+1] - a[i]
    b.append(x)
b.append(K-a[-1]+a[0])
print(K-max(b))

Solution (Python):
K,N=map(int,input().split())
i=list(map(int,input().split()))
t=i[0]+K-i[N-1]
for j in range(N-1):
  if t<i[j+1]-i[j]:
    t=i[j+1]-i[j]
print (K-t)

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

A_dif = [0]*n
A_dif[0] = A[0] + k - A[n-1]

for i in range(1,n):
  A_dif[i] = A[i]-A[i-1]

ans = k - max(A_dif)

 
print(ans)

Solution (Python):
k, n = map(int, input().split())
l = [int(x) for x in input().split()]

md = l[0] + k-l[-1]

mx = md
before = l[0]
for i in l[1:]:
    if i-before > mx:
        mx = i-before
    before = i

print(k-mx)

Solution (Python):
K , N = map ( int , input().strip().split(" " ) ) ; 
arr = list ( map ( int , input().strip().split(" ") ) ) ; 


y = K ;
for p1 in range ( N ) :
	p2 = ( p1 -1 + N )  %  N ;
	if arr[p1] > arr[p2] :
		l1 = K - arr[p1] + arr[p2] ;	
	else :
		l1 = arr[p2] - arr[p1] ;
	
	p2 = ( p1 + 1 + N ) % N ; 
	if arr[p1] > arr[p2] : 
		l2 = arr[p1] - arr[p2] ;
	else:
		l2 = K - arr[p2] + arr[p1] ;
	l = min ( l1 , l2 ) ;
	y = min ( y , l1 ) ;
print ( y ) ;

Solution (Python):
k,n = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
a.append(a[0]+k)
b = []
for i in range(len(a)-1):
    b.append(a[i+1] - a[i])
print(sum(b) - max(b))

Solution (Python):
N,K=map(int,input().split())
max1=0
list1=list(map(int,input().split()))
list2=[0]*(K+1)
for i in range(K):
    list2[i]=list1[i]
list2[K]=list1[0]+N
list3=[0]*K
for i in range(K):
    list3[i]=list2[i+1]-list2[i]

max1=max(list3)

answer=N-max1

print(answer)

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

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

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



l_max = max(l)

ans = sum(l)-l_max

print(ans)

Solution (Python):
def inputs(): return [int(x) for x in input().split()]
from collections import defaultdict
k,n = inputs()
a = inputs()
ans = min(a[-1]-a[0],k-(a[1]-a[0]))
for i in range(n-1):
    if i!=0:
        ans = min(ans,min(k-abs(a[i+1]-a[i]),k-abs(a[i-1]-a[i])))
    
print(ans)

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


d = 0
for i in range(1,n):
    if a[i]-a[i-1] >= d:
        d = a[i]-a[i-1]
    else:
        d = d

e = k + a[0] - a[-1]
if e >= d:
    d = e




print(k-d)

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

diff = (k - a[-1]) + a[0]
dmax = diff
for i in range(1, n):
   diff = a[i] - a[i-1]
   dmax = max(dmax, min(diff, k - diff))

print(k - dmax)

Solution (Python):

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

distance_max = 0
for i in range(N):
    if distance_max < A[i+1] - A[i]:
        distance_max = A[i+1] - A[i]

print(K-distance_max)

Solution (Python):
K, N = map(int, input().split())
A = list(map(int, input().split()))
diff_list = []

diff_list.append(K-A[-1] + A[0])

for i in range(1, N):
    diff_list.append(A[i]-A[i-1])


print(sum(diff_list)-max(diff_list))

Solution (Python):


import sys


def LI():
    return list(map(int, sys.stdin.buffer.readline().split()))


def I():
    return int(sys.stdin.buffer.readline())


def LS():
    return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()


def S():
    return sys.stdin.buffer.readline().rstrip().decode('utf-8')


def IR(n):
    return [I() for i in range(n)]


def LIR(n):
    return [LI() for i in range(n)]


def SR(n):
    return [S() for i in range(n)]


def LSR(n):
    return [LS() for i in range(n)]


def SRL(n):
    return [list(S()) for i in range(n)]


def MSRL(n):
    return [[int(j) for j in list(S())] for i in range(n)]




def main():
    k, n = LI()
    a = LI()

    dists = []

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

    dists.append(a[0] + k - a[-1])

    ans = sum(dists) - max(dists)

    print(ans)


main()

Solution (Python):
import numpy as np

K, N = [int(i) for i in input().rstrip().split(' ')]
A = [int(i) for i in input().rstrip().split(' ')]

x = A[0]
y = K - A[-1]
n = [int(A[i+1] - A[i]) for i in range(N-1)]
n.append(x+y)

np_list = np.array(n)
n.pop(np_list.argmax())
print(sum(n))

Solution (Python):
import numpy as np
K, N = map(int, input().split())
A = list(map(int, input().split()))
ans = 0
A = sorted(A)
new = []
for i in range(N-1):
    new.append(A[i+1]-A[i])
new.append(K + A[0] - A[-1])
new = sorted(new)
print(sum(new[:-1]))

Solution (Python):
k, n = map(int, input().split())
A = list(map(int, input().split()))
maximum = 0
for i in range(n):
    x = A[i] - A[i-1]
    if i == 0:
        x += k
    if x > maximum:
        maximum = x
print(k - maximum)

Solution (Python):

def main():
    K, N = map(int, input().split())
    A = list(map(int, input().strip().split()))
    A.append(K+A[0])
    B=[0]*(N+1)
    for i in range(N):
        B[i]=A[i+1]-A[i]
    
    
    
    
    print(K-max(B))
    
main()

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

A = sorted(A)

ans = 1000000000
for i in range(0, N):
    if i == 0:
        a = A[-1] - A[0]
        b = (K-A[i+1]) + A[0]
    if i == N-1:
        a = (K-A[i]) + A[i-1]
        b = A[-1]-A[0]
    else:
        a = (K - A[i]) + A[i-1]
        b = A[i] + (K - A[i+1])
    ans = min(ans, min(a, b))

print(ans)

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

diff = []


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


DIFF = sorted(diff)

del DIFF[-1]

print(sum(DIFF))

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

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




D = max([i-j for i,j in zip(A[1:N], A[0:(N-1)])])

z = K - A[N-1] + A[0]
if z > D:
    D = z
print(K - D)

Solution (Python):
K ,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, K - A[N-1] + A[0])

print(K - ans)

Solution (Python):
k,n=map(int,input().split())
a=list(map(int,input().split()))
e=a[1:]+[k+a[0]]
l=[abs(x-y) for x,y in zip(a,e)]
print(sum(l)-max(l))

Solution (Python):
k, n = map(int, input().split())
ai = list(map(int, input().split()))

dists = []

last = -1
for a in ai:
    if last < 0:
        last = a
        continue
    
    dists.append(a - last)
    last = a

dists.append(k - last + ai[0])

print(k - max(dists))

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

Solution (Python):
K, N = map(int, input().split(' '))
a = list(map(int, input().split(' ')))
a.sort()

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

maxDistance = max(d)
startIndex = d.index(maxDistance)
ans = 0
for i in range(N-1):
  ans += d[startIndex - i-1]

print(ans)

Solution (Python):
length, num = map(int, input().split())
dist=[int(i) for i in input().split()]

Max=0
for i in range(num-1):
    Max = max([dist[i+1]-dist[i],Max])

Max=max(Max,length-dist[-1]+dist[0])
print(length-Max)

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

distA = []

for i in range(N-1):
  distA.append( A[i + 1] - A[i] )
distA.append(A[0] + (K - A[N-1]) )
print(sum(distA) - max(distA))

Solution (Python):

K, N = map(int,input().split())
A =list(map(int,input().split()))
l = len(A)
ans = 10**9
for i in range(l):
    if (i == 0):
        ans = min(A[-1] - A[0], A[0] + K - A[1], ans)
    elif (i == l-1):
        ans = min(A[-1] - A[0], A[-2] + K - A[-1], ans)
    else:
        ans = min(K - A[i] + A[i-1], A[i] + K - A[i+1], ans)
print(ans)

Solution (Python):
K, N = map(int, input().split())
points = list(map(int, input().split()))

points.sort()


points += [p + K for p in points]


print(min(
    points[start + N - 1] - points[start]
    for start in range(N)
))

Solution (Python):


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

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




max_range = (K+A[0]-A[N-1])

for i in range(N-1):
    if max_range < A[(i+1)%K]-A[i%K]:
        max_range = A[i+1]-A[i]
        


if max_range>=K/2:
    print(K-max_range)
else:
    print(K-max_range)

Solution (Python):
from sys import stdin

k, n = [int(x) for x in stdin.readline().rstrip().split()]

l = [int(x) for x in stdin.readline().rstrip().split()]




mylist = []

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



sortlist = sorted(mylist)
length = 0
for i in range(n-1):
    length += sortlist[i]

print(length)

Solution (Python):
import sys
import os
import math

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    K, N = il()
    A = il()
    A.sort()
    ret = max(A) - min(A)

    for n in range(N - 1):
        ret = min(ret, A[n] + (K - A[n + 1]))

    print(ret)


if __name__ == '__main__':
    main()

Solution (Python):
k, n = map(int, input().split())
x = [int(x) for x in input().split()]
arr = []

arr.append(x[0]+abs(x[len(x)-1]-k))

for i in range(len(x)-1):
    arr.append(x[i+1]-x[i])


print(sum(arr) - max(arr))

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

dist = [0] * (N)

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

print(K - max(dist))

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

    shiftA = A[1:] + [K+A[0]]

    subA = [shiftA[i] - A[i] for i in range(N)]
    maxA = max(subA)
    subA.remove(maxA)

    print(sum(subA))

if __name__ == '__main__':
    main()

Solution (Python):
a, b = map(int, input().split())
c = list(map(int, input().split()))
sa = 0
for i in range(b):
    if i == 0:
        sa = c[0] - (c[b-1] - a)
    elif c[i] - c[i-1] >= sa + 1:
        sa = c[i] - c[i-1]
print(a-sa)

Solution (Python):
K, N = map(int, input().split())
houses = list(map(int, input().split()))












for i in range(N - 1):
    houses.append(K + houses[i])

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

Solution (Python):
K, N = map(int, input().split())
A = list(map(int, input().split()))
B = [K - i for i in A]
dpB = [0]*N
dpA = [0]*N

dpA[0] = A[0] + B[N-1]
dpB[0] = B[0] + A[N-1]

for i in range(N):
    if i>0:
        dpA[i] = A[i] - A[i-1]
for i in range(N):
    if i>0:
        dpB[i] = A[i] - A[i-1]
MAXA = max(dpA)
MAXB = max(dpB)
SUMA = sum(dpA) - MAXA
SUMB = sum(dpB) - MAXB




print(min(SUMA, SUMB))

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

Solution (Python):
from sys import stdin

lines = stdin.readlines()
k, n = [int(x) for x in lines[0].rstrip().split()]
a = [int(x) for x in lines[1].rstrip().split()]

diffs = [int(a[x+1]-a[x]) for x in range(len(a)-1)]
diffs.append(k - a[-1] + a[0])

print(k - max(diffs))

Solution (Python):
info = list(map(int,input().split()))
k=info[0]
n=info[1]
a = list(map(int,input().split()))
MAX=0

for i in range(n-1):
    if a[i+1]-a[i] > MAX:
        MAX=a[i+1]-a[i]
if a[0]+k-a[n-1] > MAX:
        MAX=a[0]+k-a[n-1]
print(str(k-MAX))

Solution (Python):
import numpy as np

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


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


lengths = np.concatenate([[A[0] + (K - A[-1])], np.diff(A)],0)
print(K - lengths[np.argmax(lengths)])

Solution (Python):
k,n=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
b=len(a)
diff=max(a)-min(a)
temp1=a[0]
for i in range(1,b):
    temp2=a[i]
    a[i]=a[i]-temp1
    temp1=temp2


la=k-diff
a[0]=la

print(sum(a)-max(a))

Solution (Python):
k, n = map(int, input().split())
arr = list(map(int, input().split()))

m = []
for i in range(1, n):
	m += [arr[i] - arr[i - 1]]

mn = k - arr[-1] + arr[0]
m.append(mn)
m.sort()
print(sum(m[:n-1]))

Solution (Python):
from sys import stdin
def main():
    readline=stdin.readline
    K,N=map(int,readline().split())
    A=list(map(int,readline().split()))
    B=list()
    for i in range(N):
        if A[i]==0 or A[i]==K//2:
            B.append(A[i])
        else:
            B.append(A[i])
            B.append(A[i]-K)
    B.sort()
    mi=0
    ma=0
    res=K
    for i in range(len(B)):
        if i+N-1<=len(B)-1:
            mi=B[i]
            ma=B[i+N-1]
            res=min(res,ma-mi)
        else:
            break
    print(res)
if __name__=="__main__":
    main()

Solution (Python):
import sys

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

  
b=[]
b.append(k+a[0]-a[n-1])

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

b.remove(max(b))

print(sum(b))

Solution (Python):
if __name__ == "__main__":
    K, N = list(map(int, input().split()))
    a = list(map(int, input().split()))
    d = [0 for i in range(N)]
    for i in range(N):
        if i == N - 1:
            d[i] = K - a[i] + a[0]
        else:
            d[i] = a[i+1] - a[i]
    print(sum(d) - max(d))

Solution (Python):
k,n = map(int,input().split())
A = list(map(int, input().split()))
max_L = 0
max_R = 0
left = 0
right = 0
for i in range(n):
  d = {}
  if i-1 < 0:
    d['left'] = k - A[n-1] + A[i]
    d['right'] = A[i + 1] - A[i]
  elif i + 1 > n-1:
    d['left'] = A[i] - A[i-1]
    d['right'] = k - A[i] + A[0]
  else:
    d['left'] = A[i] - A[i-1]
    d['right'] = A[i + 1] - A[i]
    
  if max_L < d['left']:
    max_L = d['left']
  if max_R < d['right']:
    max_R = d['right']

  right += d['right']
  left += d['left']
  
if right - max_R < left - max_L:
  print(right - max_R)
else:
  print(left - max_L)

Solution (Python):
K, N = list(map(int, input().split()))
an = list(map(int,input().split()))

min_list = []
for i in range(N):
    if i == 0:
        left = an[i] + K - an[-1]
        right = an[i+1] - an[i]
    elif i == N-1:
        left = an[i] - an[i-1]
        right = an[0] + K - an[N-1]
    else:
        left = an[i] - an[i-1]
        right = an[i+1] - an[i]
    min_list.append(min(K-left, K-right))
print(min(min_list))

Solution (Python):
import numpy

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

distance = numpy.empty(n,dtype=numpy.int)
distance[0] = a[0]

for i in range(1,n):
    distance[i] =  a[i] - a[i-1]

distance[0] = k - a[n-1] + a[0]

print(k - max(distance))

Solution (Python):












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

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


ans = k+10
for i in range(n):
    if i == 0:
        migi = arrA[n-1]-arrA[0]
        hidari = k - (arrA[1]-arrA[0])
        ans = min(migi,hidari,ans)
    elif i == n-1:
        migi = k -(arrA[n-1] - arrA[n-2])
        hidari = arrA[n-1]-arrA[0]
        ans = min(migi,hidari,ans)
    else:
        migi = arrA[i-1] + k-arrA[i]
        hidari = k-(arrA[i+1]-arrA[i])
        ans = min(migi,hidari,ans)

print(ans)

Solution (Python):
I=lambda:list(map(int,input().split()))
p,n=I()
l=I()
ne=[]
ma=10**9+7
for i in range(n-1):
    ne.append(abs(l[i]-l[i+1]))
if l[-1]==p:
    ne.append(l[0]-l[-1])
else:    
    ne.append(l[0]+abs(p-l[-1]))
g=sum(ne)
for i  in ne:
    ma=min(ma,g-i)
print(ma)

Solution (Python):
import collections
import math
import numpy as np
K, N = map(int, input().split(' '))

A = sorted(list(map(int, input().split(' '))))
for i in range(N):
    A.append(A[i]+K)


m = float('inf')

for i in range(N):
    kyori = A[i+N-1]-A[i]
    m = min(m, kyori)
print(m)

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

distance = []
for i in range(len(A)-1):
    distance.append(A[i]+K-A[i+1])
distance.append(max(A)-min(A))
print(min(distance))

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

li = []

for i in range(len(A) - 1):
    li.append(A[i+1] - A[i])

li.append(K + A[0] - A[N-1])

print(K - max(li))

Solution (Python):
lake_len, house_num = map(int, input().split())
house = list(map(int, input().split()))
diff = []

for i in range(house_num):
    if i != house_num - 1:
        diff.append(house[i+1] - house[i])
    else:
        diff.append(lake_len - house[i] + house[0])

diff_sort = sorted(diff, reverse=True)

print(sum(diff_sort) - diff_sort[0])

Solution (Python):
K,N =map(int,input().split())
list_A =input().strip().split()
list_B=[]
list_B.append(int(list_A[0])+(K-int(list_A[-1])))
for i in range(N-1):
    list_B.append(int(list_A[i+1])-int(list_A[i]))
print(K-max(list_B))

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

Solution (Python):
K, N = map(int, input().split())
A = list(map(int, input().split()))
B = [abs(x - y) for x, y in zip(A[1:], A)]
B += [K - A[-1] + A[0]]

print(sum(B) - max(B))

Solution (Python):
K, N = map(int, input().split()) 
A = list(map(int, input().split()))
res = [0 for _ in range (N)]
for i in range(N-1):
  res[i] = K - max(A[i+1]-A[i], A[i]-A[i-1])
res[N-1] = K - max(A[N-1]-A[N-2], A[0]+K-A[N-1])
print(min(res))

Solution (Python):
K, N = map(int, input().split())
Ai = list(map(int, input().split()))
Di = [0]*len(Ai)

for i in range(len(Ai)):
    if i == len(Ai) - 1:
        Di[i] = (K - Ai[i]) + Ai[0]
    else:   
        Di[i] = Ai[i + 1] - Ai[i]

ans = K - max(Di)

print(ans)

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

Solution (Python):
k,n=map(int,input().split())
l=list(map(int,input().split()))
l.append(k+l[0])
ans_lst=[]
ans=0
for i in range(n):
    ans_lst.append(l[i+1]-l[i])


ans=sum(ans_lst)-max(ans_lst)
print(ans)

Solution (Python):
k,n=map(int, input().split())
a=list(map(int,input().split()))
maxi=0
for i in range(n):
    if i==0:
        if max(a[1]-a[0],k-a[n-1]+a[0])>maxi:
            maxi=max(a[1]-a[0],k-a[n-1]+a[0])
    elif i!=n-1:
        if max(a[i+1]-a[i],a[i]-a[i-1])>maxi:
            maxi=max(a[i+1]-a[i],a[i]-a[i-1])
    else:
        if a[n-1]-a[n-2]>maxi:
            maxi=a[n-1]-a[n-2]
print(k-maxi)

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

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

print(K - max(D))

Solution (Python):
import sys
input = sys.stdin.readline

def main():
    n, m = map(int, input().split())
    lis = list(map(int, input().split()))
    su = []
    for i in range(m - 1):
        su.append(lis[i + 1] - lis[i])
    ou = lis[0] - lis[-1] + n
    print(sum(su) + ou - max(ou, max(su)))

if __name__ == '__main__':
    main()

Solution (Python):
K,N=map(int, input().split())
A=list(map(int, input().split()))
max_diff = 0
ck = 0
for i in range(0,N):
    if i == N -1:
        ck = abs(A[(i+1)%N] + K  - A[i])
    else:
        ck = abs(A[(i+1)%N] - A[i])
    if max_diff < ck:
        max_diff = ck
print(K - max_diff)

Solution (Python):
K, N = map(int, input().split())
distances = list(map(int,input().split()))

var = distances[0]
for i in range(N):
    distances[i] -= var
distances.append(K-distances[-1])

for i in range(N-1, 0,-1):
    distances[i] -= distances[i-1]

print(sum(sorted(distances)[:-1]))

Solution (Python):
K, N = map(int, input().split())
A_list = list(map(int, input().split()))

result1 = A_list[-1]-A_list[0]
dist = []
for i in range(N-1):
    dist.append(A_list[i+1]-A_list[i])
dist = max(dist)
result2 = K-dist
if result1>=result2:
    print(result2)
else:
    print(result1)

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


start_diff = A[0] + k - A[-1]
diff = [start_diff]
answer = 0
start = A[0]

for i in range(1, n):
    diff.append(A[i] - start)
    start = A[i]




answer = sum(diff) - max(diff)
print(answer)

Solution (Python):
k, n = (int(x) for x in input().split())
a = list([int(x) for x in input().split()])

dist_betweenHomes = list()
for i in range(len(a)):
    if i + 1 == len(a):
        d = (k - a[i]) + a[0]
    else:
        d = a[i + 1] - a[i]
    dist_betweenHomes.append(d)

maxDist = max(dist_betweenHomes)
result = k - maxDist
print(result)

Solution (Python):
K, N = map(int, input().split())
*A, = map(int, input().split())
B = [A[i + 1] - A[i] for i in range(N - 1)]
B.append(A[0] + K - A[N - 1])
print(sum(B) - max(B))

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

A = [int(x) for x in input().split()]

ans = 0

for i in range(N):
    if i == 0:
        tokei = A[-1] - A[i]
        hantokei = A[i] + K - A[i+1]
        ans = min(tokei, hantokei)
    elif i == N-1:
        tokei = K - A[i] + A[i-1]
        hantokei = A[i] - A[0]
    else:
        tokei = K - A[i] + A[i-1]
        hantokei = A[i] + K - A[i+1]
        temp = min(tokei, hantokei)
        if ans > temp:
            ans = temp

print(ans)

Solution (Python):
k,n = [int(a) for a in input().split()]
N = [int(a) for a in input().split()]
L = []
for s in range(len(N)-1):
  L.append(N[s+1] - N[s])
L.append(N[0] + k-N[-1])
print(k - max(L))

Solution (Python):
import numpy as np
k,n = map(int, input().split())
a = list(map(int, input().split()))
b = np.zeros(n)
for i in range(0,n-1):
  b[i] = a[i+1] -a[i]
  
b[n-1] = k - a[n-1] + a[0]
ans = k - max(b)
print(int(ans))

Solution (Python):
s = [int(e) for e in input().split()]
k =s[0]
n = s[1]
a=[int(e) for e in input().split()]
a_length=[]
for i in range(n-1):
    a_length.append(a[i+1]-a[i])
a_length.append(k-a[-1]+a[0])
amax = max(a_length)
print(k-amax)