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):
def main():
    K,N = (int(i) for i in input().split())
    A = [int(i) for i in input().split()]

    d = []
    n = len(A)
    for i, a in enumerate(A):
        if i == 0:
            d.append(min(A[0] + K - A[1], A[n-1] - A[0]))
        elif i == n-1:
            d.append(min(A[n-1]-A[0], K-A[n-1]+A[N-2]))
        else:
            d.append(min(K-A[i]+A[i-1], A[i]+K-A[i+1]))

    print(min(d))


if __name__ == '__main__':
    main()

Solution (Python):
k, n, *A = map(int, open(0).read().split())

dist = A[0] + (k - A[-1])
maxdist = dist
start = 0

for i in range(n - 1):
    if maxdist < A[i + 1] - A[i]:
        start = i + 1
        maxdist = A[i + 1] - A[i]

if start == 0:
    print(A[-1] - A[0])
else:
    print(A[-1] - A[start] + dist + (A[start - 1] - A[0]))

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

def distance(a1, a2):
  return abs(a1 - a2)

sum, max = 0, 0
for i in range(N):
  if (i + 1) < N:
    d = distance(An[i], An[i+1])
    sum += d
    if(d > max):
      max = d
  else:
    d = distance(An[i], K) + distance(0, An[0])
    sum += d
    if(d > max):
      max = d

print(sum - max)

Solution (Python):
line = input().rstrip().split(' ')
k = int(line[0])
n = int(line[1])

line = input().rstrip().split(' ')
a = [0] * n
for i in range(n):
    a[i] = int(line[i])

ans = 1000000
for i in range(n):
    if i - 1 > -1:
        tmp1 = k - a[i] + a[i - 1]
    else:
        tmp1 = a[n - 1] - a[i]

    if i < n - 1:
        tmp2 = k - a[i + 1] + a[i]
    else:
        tmp2 = a[i] - a[0] 

    ans = min(ans, tmp1, tmp2)

print(ans)

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

dmax = 0
for i in range(N-1):
    d = A[i+1] - A[i]
    if d > dmax:
        dmax = d
if A[N-1] - A[0] < A[0] + (K - A[N-1]):
    d = A[N-1] - A[0]
    if d > dmax:
        dmax = d
    ans = dmax
else:
    d = A[0] + (K - A[N-1])
    if d > dmax:
        dmax = d
    ans = K - dmax

print(ans)

Solution (Python):
import math




perimeter,N = map(int,input().split())
data = list(map(int,input().split()))


biggest_gap = perimeter-(data[-1]-data[0])

for i in range(1,len(data)):
    biggest_gap = max(biggest_gap,data[i]-data[i-1])

shortest_path = perimeter-biggest_gap

print(shortest_path)

Solution (Python):
k, n = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
A.append(k + A[0])

MaxD = 0
for i in range(n):
    MaxD = max(MaxD, A[i + 1] - A[i])

print(k - MaxD)

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

Solution (Python):
K, N =map(int, input().split())
A = list(map(int, input().split()))
D = [A[i+1]-A[i] for i in range(len(A) -1)]
d = A[0] + (K - A[-1])
j = max(D)
if d < j:
    ans = K-j
else:
    ans = K -d
print(ans)

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

ans=0
if max(a)<=(k/2.0) or min(a)>=(k/2.0):
  for i in range(n-1):
    ans+=abs(a[i+1]-a[i])
else:
  max_=0
  for i in range(n-1):
    max_=max(max_,abs(a[i+1]-a[i]))
  max_=max(max_,abs(a[0]-(a[n-1]-k)))
  ans=k-max_
print(ans)

Solution (Python):
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

k,n = inpl()
a = inpl()
b = []
for i in range(1,n):
    b.append(abs(a[i] - a[i-1]))
b.append(k-a[-1] + a[0])
b.sort()
print(sum(b) - b[-1])

Solution (Python):



def inp():
    return(int(input().rstrip()))
def inlt():
    return(list(map(int,input().rstrip().split())))
def insr():
    s = input().rstrip()
    return(s[:len(s) - 1])
def invr():
    return(map(int,input().rstrip().split()))

k,n = invr()
nums = inlt()
ans = min(nums[-1] - nums[0],k - (nums[1] - nums[0]))
for i in range(1,n - 1):
    
    result = min(k - (nums[i] - nums[i - 1]), \
             k - abs(nums[i + 1] - nums[i]))
    
    if result < ans:
        ans = result

ans = min(ans,k - (nums[-1] - nums[-2]))
print(ans)

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

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

max = K - A[N-1] + A[0]

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

  
print(K - max)

Solution (Python):
k,n = map(int,input().split())
s = list(map(int,input().split()))
a=[]
for num in range(n-1):

    p= s[num+1]-s[num]
    a.append(p)
b = s[0]+(k-s[-1])
a.append(b)
x = k-max(a)
print(x)

Solution (Python):
def c_traveling_salesman_around_lake():
    K, N = [int(i) for i in input().split()]
    A = [int(i) for i in input().split()]

    pos = [-(K - a) for a in A] + A[:]
    diff = [abs(pos[i + 1] - pos[i]) for i in range(len(pos) - 1)]
    ans = sum(diff[:N - 1])
    tmp = ans

    left, right = 0, N - 1
    while right != len(diff):
        tmp -= diff[left]
        tmp += diff[right]
        ans = min(ans, tmp)
        left += 1
        right += 1
    return ans

print(c_traveling_salesman_around_lake())

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

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

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

Solution (Python):

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


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

ans1 = max(a) - min(a)
ans2 = k - max(diff_list)

ans = min(ans1, ans2)


print(ans)

Solution (Python):
k, n = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
max_diff = k - a[n-1] + a[0]
for idx in range(len(a)-1):
  diff = a[idx+1] - a[idx]
  if max_diff < diff:
    max_diff = diff
max_diff = max_diff
ans = k - max_diff
print(ans)

Solution (Python):


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


min_cost = 10**8
a_len = len(a_list)

for i in range(len(a_list)):
    a = a_list[i]
    ushiro_i = 0
    mae_i = 0
    
    if i-1<0:
        ushiro_i = a_len - 1
    else:
        ushiro_i = i - 1

    
    if i+1>=a_len:
        mae_i = 0
    else:
        mae_i = i + 1

    
    kouho_1 = 0
    kouho_2 = 0
    if a_list[mae_i]-a_list[i]<0:
        kouho_1 = K - (a_list[mae_i] - a_list[i] + K)
    else:
        kouho_1 = K - (a_list[mae_i] - a_list[i])
    if a_list[i]-a_list[ushiro_i]<0:
        kouho_2 = K - (a_list[i] - a_list[ushiro_i] + K)
    else:
        kouho_2 = K - (a_list[i] - a_list[ushiro_i])
        
    min_cost = min(min_cost, kouho_1, kouho_2)


print(min_cost)

Solution (Python):
import copy

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

now = 0
ans = 2000000000000000000000000

for i in range(1, n):
    now = k-a[i]+a[i-1]
    if now < ans:
      ans = now

if a[n-1]-a[0] < ans:
  ans = a[n-1]-a[0]
        
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(4100000)

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

b.append(k-a[n-1]+a[0])
anss = max(b)
ans = k - anss
print(str(ans))

Solution (Python):

import numpy as np

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

A = np.array(A)
B = np.diff(A, n=1)

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

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

max_dist = 0
for i in range(n-1):
	cur_dist = a[i+1] - a[i]
	if cur_dist > max_dist:
		max_dist = cur_dist

cur_dist = k + a[0] - a[-1]
if cur_dist > max_dist:
	max_dist = cur_dist

print(k - max_dist)

Solution (Python):
K, N = [int(x) for x in input().split(" ")]
a = [int(x) for x in input().split(" ")]
a.sort()
a.insert(0,a[-1])
max_d = 0
for i in range(0,N):
    if a[i+1] - a[i] >= 0 and a[i+1] - a[i] >= max_d:
      max_d = a[i+1] - a[i]
    elif a[i+1] - a[i] < 0 and a[i+1] - a[i] +K >= max_d:
      max_d = a[i+1] - a[i] + K
      
print(K-max_d)

Solution (Python):
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians

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

    ans = INF
    for i in range(N):
        if i == 0:
            ans = A[i+N-1] - A[i] if A[i+N-1] - A[i] < ans else ans
        else:
            ans = K + A[(i+N-1)%N] - A[i] if K + A[(i+N-1)%N] - A[i] < ans else ans
    
    print(ans)
    

if __name__ == '__main__':
    main()

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

max = K - A[N-1] + A[0]

A.sort()

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

  
print(K - max)

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

Solution (Python):
import sys

def main():
    K, N = list(map(int, sys.stdin.readline().rstrip().split()))
    data = list(map(int, sys.stdin.readline().rstrip().split()))

    def iterate_difference(index):
        try:
            yield data[index + 1] - data[index]
        except IndexError:
            raise StopIteration

    difference = set()
    for x in range(N):
        try:
            difference.add(next(iterate_difference(x)))
        except StopIteration:
            continue
    else:
        difference.add(K - data[N - 1] + data[0])

    print(K - max(difference))

if __name__ == '__main__':
    main()

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

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

dA = []
for i in range(1, N):
    dA.append(A[i] - A[i-1])
    if i == N - 1:
        dA.append(A[0] - (A[i] - K))

dA = sorted(dA)
print(sum(dA[:N-1]))

Solution (Python):
from sys import stdin,stdout
Pi = lambda x: stdout.write(str(x) + '\n')
S = lambda x: x*(x+1) // 2
I = lambda x: 1+(2*x)
R = lambda:stdin.readline()
Ri = lambda x:map(int,x.split())
Rs = lambda x:map(str,x.split())
Rf = lambda x:map(float,x.split())
 
def main():	
	
	for x in stdin:
		k,n = Ri(x)
		A = list(Ri(R()))
		ans = A[-1] - A[0]
		for i in range(n-1):
			ans = min(ans, (A[i]-A[0]) + (k-A[i+1]+A[0]))
			
		
		Pi(ans)

if __name__=='__main__':
	main()

Solution (Python):
k,n=map(int,input().split())
List=list(map(int,input().split()))
P=[]
for i in range(n-1):
  r=List[i+1]-List[i]
  P.append(r)
P.append(k-List[n-1]+(List[0]-0))
print(sum(P)-max(P))

Solution (Python):
data = [input().split(" ") for i in range(2)]
lake = data[0]
house = data[1]
housedata = house[0]
houseend = house[int(lake[1])-1]
result = []
result.append(int(housedata)+int(lake[0])-int(houseend))
for detail in house:
  if detail!=housedata:  
    aida = int(detail) - int(housedata)
    result.append(int(aida))
    housedata=detail
max = max(result)
print(int(lake[0])-max)

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

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

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

if __name__ == "__main__":
    main()

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

Solution (Python):
K,N = map(int,input().split(" "))
A = [int(i) for i in input().split(" ")]
a1 = [i for i in A if i<=K/2]
a2 = [j for j in A if j>K/2]

Max = 0
if len(a1)==0:
    print(a2[-1]-a2[0])
elif len(a2)==0:
    print(a1[-1]-a1[0])
else:
    for i in range(len(a1)-1):
        if a1[i+1] - a1[i] > Max:
            Max = a1[i+1] - a1[i]
            
    for j in range(len(a2)-1):
        if a2[j+1] - a2[j]>Max:
            Max = a2[j+1] - a2[j]
            
    if a1[0]+K-a2[-1]>Max:
        Max = a1[0]+K-a2[-1]
        
    if a2[0]-a1[-1]>Max:
        Max = a2[0]-a1[-1]
        
    print(K-Max)

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

Solution (Python):


nums = [int(e) for e in input().split()]

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

short = 0



n.append(nums[0] + n[0])





for i in range(nums[1]):
    
    
    if n[i+1] - n[i] >= short:
        short = n[i+1] - n[i]

print(nums[0] - short)

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

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

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

ans=0
B=sorted(A)

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

lsort=sorted(l)
for i in range(N-1):
  ans+=lsort[i]
print(ans)

Solution (Python):

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

n_prev= a[n-1]-k

m=0

for nn in a:
    if (nn-n_prev) > m:
        m=nn-n_prev
        res=(k-m)
    n_prev=nn

print(res)

Solution (Python):

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

for i in range(n):
    a.append(a[i]-k) 
a.sort()
s = [0]*(n+1)
for i in range(n+1):
    s[i] = a[i+n-1] - a[i]
    
print(min(s))

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

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

k = k_n[0]
n = k_n[1]


l = 0
l_min = float('inf')

for i in range(n):
  
  if i == 0:
    l_right = a[0] + a[n-1]
  else:
  	l_right = k - (a[i]-a[i-1])
    
  
  if i == n-1:
    l_left = a[n-1] - a[0] 
  else:
    l_left = k - (a[i+1]-a[i])
  
  if l_right <= l_left:
    l = l_right
  else:
    l = l_left
    
  if l < l_min:
    l_min = l
  else:
    pass
    
print(l_min)

Solution (Python):
from collections import deque

k, n = [int(i) for i in input().split()]
data = [int(i) for i in input().split()]

d = deque(data)
d.appendleft(0)
d.pop()

bet = [i-j for i, j in zip(data, d)]

bet[0] += k - data[-1]

print(k - max(bet))

Solution (Python):



import sys


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


def resolve():
    k, n = map(int, input().split())
    a_list = list(map(int, input().split()))

    max_distance = 0

    for i in range(len(a_list)):
        if i == 0:
            continue
        else:
            distance = a_list[i] - a_list[i-1]
            if max_distance < distance:
                max_distance = distance
                max_address_1 = i - 1
                max_address_2 = i

    first_a = a_list[0]
    last_a = a_list[n-1]

    distance = first_a + (k - last_a)

    if max_distance <= distance:
        
        move_distance = last_a - first_a
    else:
        
        move_distance = a_list[max_address_1] + (k - a_list[max_address_2])

    print(move_distance)




if __name__ == "__main__":
    resolve()

Solution (Python):
k, n = map(int, input().split())
lst = list(map(int, input().split()))
lst.sort()
dlst = list()

for i in range(n):
    if i == 0:
        continue
    dlst.append(lst[i] - lst[i - 1])

if lst[0] == 0:
    dlst.append(k - lst[n - 1])
else:
    dlst.append(k - lst[n - 1] + lst[0])

dlst.sort(reverse=True)
dlst.pop(0)

print(sum(dlst))

Solution (Python):


import sys
import math


debug = False

def log(text):
    if debug:
        print(text)

def parse_input(lines_as_string = None):

    global debug
    lines = []
    if lines_as_string is None:
        debug = False
        
        
        lines.append(input())
        lines.append(input())
    else:
        debug = True
        lines = [e for e in lines_as_string.split("\n")][1:-1]
    
    (k, n) = [int(e) for e in lines[0].split(" ")]
    a = [int(e) for e in lines[1].split(" ")]

    return (k, n, a)


def solve(k, n, a):


    result = k+1
    for i in range(n):
        
        if a[i-1] < a[i]:
            right_dist = k - a[i] + a[i-1]
        else:
            right_dist = a[i-1] - a[i]
        
        if debug:
            log("%d, %d, %d" % (i, n, (i+1) % n))
        if a[i] < a[(i+1) % n]:
            left_dist = a[i] + k - a[(i+1) % n]
        else:
            left_dist = a[i] - a[(i+1) % n]
        
        result = min([result, right_dist, left_dist])
    
    return  result


def main():
    
    result = solve(*parse_input())
    if isinstance(result, list):
        for r in result:
            print("%s" % r, sep='')
    else:
        print("%s" % result, sep='')

if __name__ == '__main__':

    main()

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

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

Solution (Python):
k,n = map(int, input().split())
A = [int(x) for x in input().split()]
c=[]
for i in range(n-1):
  c.append(A[i+1]-A[i])
c.append(k-A[n-1]+A[0])
print(k-max(c))

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

Solution (Python):


import sys
 
stdin = sys.stdin
inf = 1 << 60
mod = 1000000007
 
ni      = lambda: int(ns())
nin     = lambda y: [ni() for _ in range(y)]
na      = lambda: list(map(int, stdin.readline().split()))
nan     = lambda y: [na() for _ in range(y)]
nf      = lambda: float(ns())
nfn     = lambda y: [nf() for _ in range(y)]
nfa     = lambda: list(map(float, stdin.readline().split()))
nfan    = lambda y: [nfa() for _ in range(y)]
ns      = lambda: stdin.readline().rstrip()
nsn     = lambda y: [ns() for _ in range(y)]
ncl     = lambda y: [list(ns()) for _ in range(y)]
nas     = lambda: stdin.readline().split()

k, n = na()
a = na()

ans = inf

for i in range(n):
    if i + 1 == n:
        ans = min(ans, k - ((k - a[i]) + a[0]), k - abs(a[i] - a[i - 1]))
    elif i == 0:
        ans = min(ans, k - (a[i] + (k - a[-1])), k - abs(a[i] - a[i + 1]))
    else:
        ans = min(ans, k - abs(a[i] - a[i - 1]), k - abs(a[i] - a[i + 1]))
print(ans)

Solution (Python):
a=input().split(" ")
K,N=[int(i) for i in a]
lst=[int(i) for i in input().split(" ")]
lst1=[]
for i in range(len(lst)):
    lst1.append(lst[i]+K)
lst2=[]
for i in range(len(lst)):
    lst2.append(lst[i]+K*2)
lst=lst+lst1+lst2
dist=[]
for i in range(len(lst)-N):
    dist.append(abs(lst[i]-lst[i+N-1]))
print(min(dist))

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

Solution (Python):
k,n=map(int,input().split())
l=list(map(int,input().split()))
s=0
a=[]
for i in range(0,n-1):
    a.append(l[i+1]-l[i])
a.append(k-l[-1]+l[0])
a.sort()
s=sum(a)
s-=a[-1]
print(s)

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

Solution (Python):
k, n = map(int, input().split())
lst = []
lst = list(map(int, input().split()))




wmax = 0

for i in range(len(lst) - 1):
    w = lst[i + 1] - lst[i]
    if w > wmax:
        wmax = w

judge = [lst[0] + k - lst[-1], wmax]

print(k - max(judge))

Solution (Python):
K,N=map(int,input().split())
mtrx=list(map(int,input().split()))  
mtrx.append(K+mtrx[0])
length = []
for i in range(len(mtrx)-1):
    length.append(mtrx[i+1]-mtrx[i])
print(K-max(length))

Solution (Python):

K,N = map(int,input().split())
A   = list(map(int,input().split()))
Dist=[None]*len(A)
for i in range(len(A)-1):
    Dist[i] = A[i+1]-A[i]
Dist[i+1]=K-A[len(A)-1]+A[0]
MD=K-max(Dist)
print(MD)

Solution (Python):
K, N = map(int, input().split())
A = list(map(int, input().split()))
A.append(K)
B = 0
x = 1

for a in A:
  if A[x] == K:
    break
  elif A[x] - a > B:
    B = A[x] - a
  
  x += 1

C = K + A[0] - A[N-1]

if C == B:
  print(K - B)
elif C > B:
  print(K - C)
elif B > C:
  print(K - B)

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

print(k-d)

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

m=a[0]+(k-a[len(a)-1])
for i in range(len(a)-1):
    m=max(m,a[i+1]-a[i])

print(k-m)

Solution (Python):
import copy

l = int(input().split()[0])
lh = int(l / 2)
houses = list(map(int, input().split()))

houses2 = copy.deepcopy(houses)
houses2.append(houses2[0])
houses2 = houses2[1::]
distances = [abs(h1 - h2) for (h1, h2) in zip(houses, houses2)]
route = sum(sorted([abs(d - l) if d > lh else d for d in distances])[:-1:])

print(route)

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

n -= 1
d_right = A[n] - A[0]
d_left = d_right

for i in range(1, n):
	d = k - A[i] + A[i - 1]
	if d < d_right:
		d_right = d

for j in range(0, n):
	l = k + A[j] - A[j + 1]
	if l < d_left:
		d_left = l

print(min(d_left, d_right))

Solution (Python):
K, N = map(int, input().split())
A = list(map(int, input().split()))
def main():
    max_index = N-1
    max_v = K -A[-1] +A[0]
    
    for i in range(N-1):
        if max_v < A[i+1] -A[i]:
            max_index = i
        max_v = max(A[i+1] -A[i], max_v)
    if max_index == N-1:
        print(A[max_index] - A[0])
        return
    
    
    
    else:
        print(K -A[max_index+1] +A[max_index])
        return
main()

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

ans = float("inf")
for i in range(1, n):
    ans = min(ans, A[i-1]+k-A[i])
ans = min(ans, A[n-1])
for i in range(n-1):
    ans = min(ans, A[i]+k-A[i+1])
ans = min(ans, A[n-1]-A[0])
print(ans)

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

if a[n-1]-a[0] <= k-a[n-1]+a[0]:
    print(a[n-1]-a[0])
else:
    for i in range(n):
        ans=max(ans,a[i]-a[i-1])
    ans=max(ans,k-a[n-1]+a[0])
    print(k-ans)

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

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

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

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

print(k - max(d))

Solution (Python):
from collections import deque
import heapq
import itertools
import math

k,n=map(int,input().split())
a=list(map(int,input().split()))
sum=0
max_root=0
tmp = k-(a[-1]-a[0])
max_root=tmp
sum+=tmp
for i in range(len(a)-1):
    tmp = a[i+1]-a[i]
    if tmp > max_root:
        max_root=tmp
    sum+=tmp

print(k-max_root)

Solution (Python):
k,n = list(map(int, input().split(' ')))
places = list(map(int, input().split(' ')))
dists = []

sum = 0
max = 0
for i in range(n):
  if i < (n - 1):
  	tmp = places[i+1]-places[i]
  else:
    tmp = k - places[i] + places[0]
  dists.append(tmp)
  sum += tmp
  if max < tmp:
    max = tmp
print (sum - max)

Solution (Python):

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

A = input()

A_list = A.split(' ')
for i in range(len(A_list)):
    A_list[i] = int(A_list[i])

amari = K-int(A_list[N-1])

aida_list = [0]*len(A_list)
for i in range(len(A_list)-1):
  aida_list[i] = A_list[i+1] - A_list[i]

aida_list[len(A_list)-1] = K - sum(aida_list)


max_ = max(aida_list)


aida_list.remove(max_)

ans = sum(aida_list)



print(ans)

Solution (Python):
import sys


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

left = a[n-1] - a[0]
right = k + 1

for i in range(n):
    if i == n-1:
        tmp = k - (a[0] + (k - a[i]))
    else:
        tmp = k - (a[i+1] - a[i])
    right = min(right, tmp)

print(min(left, right))

Solution (Python):
k, n = map(int, input().split())
lis = list(map(int, input().split()))
dislis = []
num_pre = lis[-1]
for num in lis:
    dislis.append(min(k-abs(num - num_pre),abs(num - num_pre)))
    num_pre = num

print(k-max(dislis))

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

maxi = 0

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

    maxi = max(maxi, x)

x = a[-1] - a[0]

if k - x < x:
    x = k - x

maxi = max(maxi, x)

print(k - maxi)

Solution (Python):
import sys
readline=sys.stdin.buffer.readline
K, N = map(int, readline().rstrip().split())
s= readline().rstrip().split()
max = 0
for i in range(N):
    if i == N-1:
        if max <  (int(s[0])+K) - int(s[i]):
            max = (int(s[0])+K) - int(s[i])
    else: 
        if max <  int(s[i+1])-int(s[i]):
            max = int(s[i+1])-int(s[i])

print(K-max)

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

diff = 0
largest_diff = 0
sumNum = 0 

for x in range(n-1):
	diff = a[x+1]-a[x]
	sumNum += diff
	if largest_diff < diff:
		 largest_diff = diff

last_diff = k-a[n-1]+a[0]
sumNum += last_diff
if largest_diff < last_diff:
	largest_diff = last_diff

print(sumNum-largest_diff)

Solution (Python):
k, n = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
a_ = a+[a[0]+k]
p = []
for i in range(len(a_)-1):
  p.append(a_[i+1]-a_[i])


max_value = max(p)
max_index = p.index(max_value)


i=1
j=0
ans =0
while True:

  try:
    ans += a_[max_index+i+1] - a_[max_index+i] 
    i += 1
    
  except:
    if j+1 == max_index+1:
      break
    ans += a_[j+1]-a_[j]
    j+=1
    

print(ans)

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

for i in range(1, n - 1):
    ref = k - (a[i + 1] - a[i])
    if ref < ans:
        ans = ref

print(ans)

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

    A.append(K+A[0])
    ans = K

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







    return 0


if __name__ == '__main__':
    main()

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

x_plus = [K-A[-1]+A[0]] + [A[i+1] - A[i] for i in range(N-1)]
print(K - max(x_plus))

Solution (Python):


t = input().split()
k = int(t[0])
n = int(t[1])

a = []
t = input().split()
for c in t:
    a.append(int(c))

d = a[0] + k - a[-1]

for i in range(1, n):
    dd = a[i] - a[i-1]
    if dd > d:
        d = dd
print(k-d)

Solution (Python):
m = input().split()
K = int(m[0])
N = int(m[1])

A = input().split()
a = [0] * N

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


Sum = 0
n = N -1
for x in range(N):
  if x == n:
    Sum += (K - a[n]) + a[0]
  else:
    Sum += a[x+1] - a[x]

ans = [0] * N
for k in range(N):
  if k == n:
    ans[k] = (K - a[n]) + a[0]
  else:
    ans[k] = a[k+1] - a[k]

l = max(ans)

min_road = Sum - l
print(min_road)

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

max = 0

for i in range(1,n):
  if abs(a[i] - a[i-1] ) > max:
    max = abs(a[i] - a[i-1])

if abs(k - a[-1]) + a[0] > max:
  max = abs(k - a[-1]) + a[0]


dist = k - max
print(dist)

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

Solution (Python):
K,N= map(int,input().split())
A=list(map(int,input().split()))
ans=0
mx=0
for i in range(len(A)-1):
    ans+=abs(A[i]-A[i+1])
    mx = max(mx,abs(A[i]-A[i+1]))
ans+=K-A[len(A)-1]+A[0]
mx = max(mx,K-A[len(A)-1]+A[0])

print(ans-mx)

Solution (Python):
k, n = list(map(int, input().split()))
a = list(map(int, input().split()))
sum = 0
d = []
for i in range(n):
    d.append(a[i]-a[0])
c = []
for i in range(n-1):
    sum = sum + d[i+1]-d[i]
    c.append(d[i+1]-d[i])
c.append(k-sum)
c.sort()
print(k-c[-1])