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):
l = input().split()
L = [int(c) for c in l]
K = L[0]
N = L[1]
A = [int(b) for b in input().split()]

A_delta = [A[0] + K - A[N-1]]
for n in range(N-1):
  A_delta.append(A[n+1] - A[n])
 
print(K - max(A_delta))

Solution (Python):
import numpy as np

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

diffs = np.diff(np.array(a_list))
diff_max = max(diffs.max(), a_list[0] + (k - a_list[-1]))

print(k - diff_max)

Solution (Python):
k, n = map(int, input().split(' '))
a = list(map(int, input().split(' ')))
a.append(k+a[0])

max_value = -1
ans = 0
for i in range(1, n+1):
    tmp_d = a[i] - a[i-1]
    ans += tmp_d
    max_value = max(max_value, tmp_d)
ans -= max_value
print(ans)

Solution (Python):
K , N = map(int,input().split())
arr = list(map(int,input().split()))
add = 0
maxDist = -1
arr.sort()
dp = [0 for  _ in range(N) ]
for i in range(N-1):
	dp[i+1] = arr[i+1]-arr[i]
dp[0] = (K-arr[N-1])+arr[0]
for i in range(N):
	add += dp[i]
	maxDist = max(maxDist,dp[i])
print(add-maxDist)

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

A_n.sort()

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

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

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

Solution (Python):
k,n=map(int, input().split())
a=list(map(int, input().split()))
dist=[0]*n

for i in range(n):
    if i==n-1:
        dist[i]=k+a[0]-a[i]
    else:
        dist[i]=a[i+1]-a[i]
print(k-sorted(dist,reverse=True)[0])

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

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

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

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

if max_dist < lst[0] + (K-lst[-1]):
      max_dist = lst[0] + (K-lst[-1])

print(K - max_dist)

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

    print(k - max(a_))


if __name__ == "__main__":
    main()

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

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


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

Solution (Python):


import sys
import math

sys.setrecursionlimit(10 ** 6)

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

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

ans = A[-1] - A[0]

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

print(ans)

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

cost = 0
maxcost = 0



for i in range(len(A)):
    if i == 0:
        cost += A[i]
        
        continue
    elif i == len(A)-1:
        tm = A[i] - A[i - 1]
        maxcost = max(maxcost, tm)
        cost += tm

        tm = KN[0] - A[i]
        maxcost = max(maxcost,tm+A[0])
        
        cost += tm

    else:
        tm = A[i] - A[i-1]
        maxcost = max(maxcost, tm)
        cost += tm
    

print(cost-maxcost)

Solution (Python):

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

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


house_point_diff = [house_point[i+1] - house_point[i] for i in range(n-1)]

house_point_diff.append(k + house_point[0] - house_point[n-1])



print(k-max(house_point_diff))

Solution (Python):

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

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


house_point_diff = [house_point[i+1] - house_point[i] for i in range(n-1)]

house_point_diff.append(k + house_point[0] +  - house_point[n-1])



print(k-max(house_point_diff))

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

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

Solution (Python):
import numpy as np
K,N=map(int, input().split())
A=list(map(int, input().split()))
A = np.array(A)
distance_list = A[1:N] - A[0:N-1]
distance_list = np.append(distance_list, K-A[N-1]+A[0])
print(K-max(distance_list))

Solution (Python):



import sys
input = sys.stdin.readline

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

if __name__ == '__main__':
    main()

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

maximum = K-A[-1]+A[0]

for i in range(1, N):
    d = A[i] - A[i-1]
    if maximum < d:
        maximum = d

print(K-maximum)

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

d = []
for i in range(N-1):
    if A[i+1] - A[i] > K/2:
        d.append(K-A[i+1] + A[i])
    else:
        d.append(A[i+1] - A[i])

if K - A[N-1] + A[0] > K/2:
    d.append(A[N-1] - A[0])
else:
    d.append(K - A[N-1] + A[0])
print(sum(d)-max(d))

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

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

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

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

li=[(k-a[n-1])+a[0]]

[li.append(-(a[x]-a[x+1])) for x in range(n-1)]


print(k-max(li))

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):
  ans = min(ans, k-max(a[i],a[i-1])+min(a[i],a[i-1]))
print(ans)

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

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

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

x = [abs(A[n] - A[n+1]) for n in range(N-1)] + [K - A[-1] + A[0]]

print(K - max(x))

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

dmax = K - A[N-1] + A[0]
apre = -(K - A[N-1])
for a in A:
  d = a - apre
  if d > dmax:
    dmax = d
  apre = a

print(K - dmax)

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

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

houses = [int(value) for value in input().split()]


distance = [0] * n

for i in range(n):
    distance[i] = houses[int((i+1)%n)] - houses[i]
    if distance[i] < 0:
        distance[i] = min(abs(distance[i]), distance[i]+k)

max_distance = max(distance)

sum_distance = 0
for dis in distance:
    sum_distance += dis

sum_distance -= max_distance

print(sum_distance)

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

Solution (Python):
K,N = map(int, input().split())
l = []
A = []
for i in input().split():
  A.append(int(i))


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

print(min(l))

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

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

A.insert(0, 0)
A.append(K)



start = A[1] - A[0]
goal = A[-1] - A[-2]

mixi = 0
sum_len = 0



SorG = start + goal

for i in range(len(A) - 1):
    if A[i+1] - A[i] > mixi:
        mixi = A[i+1] - A[i]
    sum_len += A[i+1] - A[i]

if max(SorG, mixi) == SorG or SorG == mixi:
    result = sum_len - (start + goal)
elif max(SorG, mixi) == mixi:
    result = sum_len - mixi

print(result)

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

for i in range(N):
    min = 0
    if i == N-1:
        min = abs(array[0] - array[N-1])
        if min>=K/2:
            min = abs(K-min)
        array_distance.append(min)
    else:
        min = abs(array[i] - array[i+1])

        array_distance.append(min)

array_distance= sorted(array_distance, reverse = True)



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

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

gap=[ ]
for i in range(N-1):
    gap.append(L[i+1]-L[i])

gap.append(K-L[N-1]+L[0])
print(K-max(gap))

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

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

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

for i in range(N):
    min = 0
    if i == N-1:
        min = abs(array[0] - array[N-1])
        if min>=K/2:
            min = abs(K-min)
        array_distance.append(min)
    else:
        min = abs(array[i] - array[i+1])
        if min>=K/2:
            min = abs(K-min)
        array_distance.append(min)

array_distance= sorted(array_distance, reverse = True)



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

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

an_minus = [an[i+1] - an[i] for i in range(n-1)]
an_minus.append(an[0] + k-an[n-1])

print(k-max(an_minus))

Solution (Python):
l = input().split(" ")
j = input().split(" ")
k = int(l[0])
n = int(l[1])
x = 0
m = k-int(j[-1])+int(j[0])
for i in range(n-1):
  d = int(j[i+1]) - int(j[i])
  x = max(x,d)
x = max(x,m)
dt = k - int(x)
print(dt)

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

Solution (Python):
KN = input().split(' ')
K = int(KN[0])
N = int(KN[1])
M = K/2
Al = input().split(' ')
A = []

for home in Al:
  A.append(int(home))

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

print(K-m)

Solution (Python):
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
    k,n=map(int,input().split())
    A=[int(_) for _ in input().split()]
    max_len=(k-A[-1])+A[0]
    for i in range(n-1):
        max_len=max(max_len,A[i+1]-A[i])
    print(k-max_len)

if __name__=='__main__':
    main()

Solution (Python):
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
    k,n=map(int,input().split())
    A=[int(_) for _ in input().split()]
    max_len=(k-A[-1])+A[0]
    for i in range(n-1):
        max_len=max(max_len,A[i+1]-A[i])
    print(k-max_len)

if __name__=='__main__':
    main()

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

max_n=0

for i in range(n-1):
  range_n=a[i+1]-a[i]
  if range_n >max_n:
    max_n=range_n

range_n=k-(a[n-1]-a[0])
if range_n > max_n:
  max_n=range_n
print(k-max_n)

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

for i in range(N-1):
    langth = List[i+1] - List[i]
    if langth > max:
        max = langth

langth = 0

langth = K - (List[N - 1] - List[0])
if langth > max:
    max = langth

print(K-max)

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

max = 0

for i in range(n):
    if i == n - 1:
        t = k - a[i] + a[0]
    else:
        t = a[i+1] - a[i]

    if t > max:
        max = t

print(k-max)

Solution (Python):

DATA = """
20 3
5 10 15
""".split("\n")

def get_debug_line():
	for i in DATA:
		yield i

if 1:
	get_line = input
else:
	get_line = get_debug_line().__next__
	get_line()

K, N = [int(i) for i in get_line().strip().split(" ")]
A = [int(i) for i in get_line().strip().split(" ")]

A.append(A[0] + K)


p = [A[i+1] - A[i] for i in range(N) ]

p.sort()
print (K - p[-1])

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

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

range = k - (List[n - 1] - List[0])
if range > max:
    max = range

print (k - max)

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

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

l.remove(max(l))
print(sum(l))

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

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

l.remove(max(l))
print(sum(l))

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

x = [abs(A[n] - A[n+1]) for n in range(N-1)] + [K - A[-1] + A[0]]

print(K - max(x))

Solution (Python):
a=input().split(" ")
k=int(a[0])
n=int(a[1])
b=input().split(" ")
num=[]
for i in range(n):
    num.append(int(b[i]))

num=sorted(num)
dis_list=[]
for i in range(n):
    if i==0:
        dis=num[0]+k-num[n-1]
    else:
        dis=num[i]-num[i-1]
    dis_list.append(dis)
dis_list=sorted(dis_list)
print(k-dis_list[n-1])

Solution (Python):
k, n = (int(x) for x in input().split())
A = [int(x) for x in input().split()]
res = 10 ** 12
for i in range(n):
  if i == 0:
    res = min(res, max(A[i+1] - A[i], k - (A[i+1] - A[i])), max(A[n-1] - A[0], k - (A[n-1] - A[0])))
  if 0 < i < n-1:
    res = min(res, max(A[i+1] - A[i], k - (A[i+1] - A[i])), max(A[i] - A[i-1], k - (A[i] - A[i-1])))
  else:
    res = min(res, max(A[i] - A[0], k - (A[i] - A[0])), max(A[i] - A[i-1], k - (A[i] - A[i-1])))
print(res)

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

A.append(A[0] + K)

L = 0

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

print(K-L)

Solution (Python):
K, N = map(int, input().split())
A = sorted(list(map(int, input().split())))
A.append(A[0] + K)
ans = 0

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

print(K - ans)

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

s = []

for i,j in zip(l[1:],l):
    s.append(i-j)

s.append(k + l[0] - l[-1])

print(k - max(s))

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

ll = l[:]

ll.append(k)
ll.pop(0)
s = []
x = (l[0] + k) - l[-1]


for i,j in zip(l,ll):
    s.append(j - i)

print(k - max(s+[x]))

Solution (Python):
stdin = open(0).read().split('\n')
K, N = map(int,stdin[0].split())
A = list(map(int,stdin[1].split()))
max = K-A[-1]+A[0]
for i in range(N-1):
    if A[i+1]-A[i] > max:max=A[i+1]-A[i]
print(K-max)

Solution (Python):
m, n = map(int, input().split(' '))
arr = list(map(int, input().split(' ')))
ans = 0
MAX = 0
now = 0
for i in range(n):
    if i == n-1:
        now = m + arr[0] - arr[n-1]
    else:
        now = arr[i+1]-arr[i]
    if now > MAX:
        MAX = now
    ans += now
print(ans-MAX)

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

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

Solution (Python):

import sys
sys.setrecursionlimit(10**8)
INF = float("inf")


def solve(K: int, N: int, A: "List[int]"):

    B = [abs((A[i]-A[i-1]) % K) for i in range(N)]
    print(K-max(B))

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    K = int(next(tokens))  
    N = int(next(tokens))  
    A = [int(next(tokens)) for _ in range(N)]  
    solve(K, N, A)


if __name__ == '__main__':
    main()

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

diffs = list()
max_diff = 0
for i in range(n):
    diff = 0
    if i == n-1:
        diff = k + a[0] - a[i]
    else:
        diff = a[i+1] - a[i]

    if max_diff < diff:
        max_diff = diff
    diffs.append(diff)

print(sum(diffs) - max_diff)

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

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

Solution (Python):
from __future__ import print_function

import sys

import re
import array
import copy
import functools
import operator

import math
import string
import fractions
from fractions import Fraction
from fractions import gcd



import collections
import itertools
import bisect

import random
import time

import heapq
from heapq import heappush
from heapq import heappop
from heapq import heappushpop
from heapq import heapify
from heapq import heapreplace
from queue import PriorityQueue as pq
from queue import Queue

from itertools import accumulate

from collections import deque
from collections import Counter

from operator import mul
from functools import reduce

input = sys.stdin.readline


def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)
    return


def lcm(n, m):
    return int(n * m / gcd(n, m))


def coprimize(p, q):
    common = fractions.gcd(p, q)
    return (p // common, q // common)


def combinations_count(n, r):
    r = min(r, n - r)
    numer = reduce(mul, range(n, n - r, -1), 1)
    denom = reduce(mul, range(1, r + 1), 1)
    return numer // denom


def find_gcd(list_l):
    x = reduce(gcd, list_l)
    return x


def main():
    k, n = map(int, input().strip().split())
    a = list(map(int, input().strip().split()))

    a.append(a[0]+k)
    ans = sys.maxsize
    for i in range(n):
        ans = min(k - (a[i+1] - a[i]), ans)
    print(min(ans, a[n-1] - a[0]))


if __name__ == '__main__':
    main()

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

max_gap = max([abs(a_list[i-1] - a_list[i]) for i in range(1, n)])
if max_gap < (a_list[0] + k - a_list[-1]):
    max_gap = a_list[0] + k - a_list[-1]
print(k - max_gap)

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

A = sorted(A)

diff = []
for i, a in enumerate(A[1:]):
    diff.append(a-A[i])

diff.append(K-A[N-1]+A[0])
print(K-max(diff))

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

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

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
printV = lambda x: print(*x, sep="\n")
printH = lambda x: print(" ".join(map(str,x)))
def IS(): return sys.stdin.readline()[:-1]
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LII(rows_number): return [II() for _ in range(rows_number)]
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]

def main():
	k,n = MI()
	a = LI()
	b = [0]*n
	for i in range(n):
		if i == n-1:
			b[i] = a[0]+k-a[i]
		else:
			b[i] = a[i+1]-a[i]
	b.sort()
	print(k-b[-1])


if __name__ == '__main__':
	main()

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

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

Solution (Python):
from sys import stdin
from collections import deque
q=deque()
K,N= list(map(int, (stdin.readline().strip().split())))
A=list(map(int, (stdin.readline().strip().split())))
max=A[1]-A[0]
home=0
home_B=0
place=0
kyori=0
for i in range(N-1):
    if max< A[i+1]-A[i]:
        max=A[i+1]-A[i]
        place=i
B=A[place]
C=A[place+1]-K
D=B-C
if A[-1]-A[0]>D:print(D)
else:print(A[-1]-A[0])

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

K, N = MAP()
A = LIST()
diff = K - A[-1] + A[0]
d = K - A[-1] + A[0]
if N == 2:
  print(min(d, A[1] - A[0]))
  exit()
for i in range(1, N):
  d += A[i] - A[i-1]
  diff = max(diff, A[i] - A[i-1])
print(d - diff)

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

K, N = MAP()
A = LIST()
diff = abs(K - A[-1] + A[0])
d = abs(K - A[-1] + A[0])
if N == 2:
  print(min(d, A[1] - A[0]))
  exit()
for i in range(1, N):
  d += abs(A[i] - A[i-1])
  diff = max(diff, abs(A[i] - A[i-1]))
print(d - diff)

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

d_max = 0
for i in range(n):
  if i==n-1:
    dis = a[0] + k - a[i]
  else:
    dis = a[i+1] - a[i]
  if d_max < dis:
    d_max = dis

print(k - d_max)

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

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

Solution (Python):
K,N=map(int,input().split())
A=[int(s) for s in input().split(" ")]

Smax=0
for i in range(N):
    S=0
    if i!=N-1:
        if A[i+1]>A[i]:
            S=A[i+1]-A[i]
        else:
            S=A[i]-A[i+1]
    else: 
        if A[0]>A[-1]:
            S=A[0]-A[-1]
        else:
            S=A[-1]-A[0]
    
    if S>K/2:
        S=K-S
    if Smax<S:
        Smax=S

print(K-Smax)

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

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
import numpy as np

K, N = MAP()
A = LIST()
A.append(A[0]+K)

B = np.zeros(N)
for i in range(N):
  		B[i] = A[i+1] - A[i]

print(int(K - max(B)))

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


d1 = k - (a[0] + (k-a[n-1]))


d = []
for x in range(len(a)):
    y = a[x] - a[x-1]
    d.append(y)

d2 = k - max(d)
print(min(d1,d2))

Solution (Python):

K,N = map(int,input().split())
nums = list(map(int,input().split()))
last_to_first = nums[0] + (K - nums[-1])
diffs = [last_to_first]
for i in range(1,N):
    diffs.append(nums[i] - nums[i - 1])
print(sum(diffs) - max(diffs))

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


ans = int(K) - maxD
print(ans)

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

dis=[]
dis.append(k-(a[-1]-a[0]))
for i in range(len(a)-1):
    dis.append(a[i+1]-a[i])

print(k-max(dis))

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

Solution (Python):
import sys
input = lambda: sys.stdin.readline().rstrip()
input_nums = lambda: list(map(int, input().split()))

def main():
    K, N = input_nums()
    A = input_nums()
    dist = []
    for i in range(len(A)-1):
        dist.append(A[i+1]-A[i])
    dist.append(K+A[0]-A[-1])
    maxv = max(dist)
    print(sum(dist) - maxv)
    

if __name__ == '__main__':
    main()

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

k = kn[0]
n = kn[1]

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



print(sum(distance) - max(distance))

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

distancies = []
for i, Ai in enumerate(A):
    current = i
    to = (i + 1) % len(A)
    distance = A[to] - A[current] if to != 0 else K - A[current] + A[0]
    distancies.append(distance)

answer = K - max(distancies)

print(answer)

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

distancies = []
for i, Ai in enumerate(A):
    current = i
    to = (i + 1) % len(A)
    distance = A[to] - A[current] if i < len(A) - 1 else K - A[current] + A[0]
    distancies.append(distance)

answer = K - max(distancies)

print(answer)

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

if __name__ == '__main__':
    main()

Solution (Python):
import statistics

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

for num, i in enumerate(a[:]):
  if num == (n - 1):
    dist.append(abs((k + a[0]) - i))
  else:
    dist.append(abs(a[num + 1] - i))
ind = dist.index(max(dist))
dist.pop(ind)
print(sum(dist))

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

Solution (Python):
"""
import random
import functools
import copy
import bisect
import array
import re
import collections
import heapq
import fractions
import itertools
import string
import math
from operator import itemgetter as ig
from bisect import bisect_left, bisect_right, insort_left, insort_right
from itertools import permutations, combinations, product, accumulate, groupby
from heapq import heappush, heappop
from collections import deque, defaultdict, Counter
import sys
sys.setrecursionlimit(10 ** 7)


inf = 10 ** 20
INF = float("INF")
mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)]
ddn9 = ddn + [(0, 0)]
'''for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:'''
"""
import sys
sys.setrecursionlimit(10 ** 7)


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



def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]


def ws(): return sys.stdin.readline().split()


def si(): return int(sys.stdin.readline())  


def ss(): return input()


def hi(n): return [si() for _ in range(n)]


def hs(n): return [ss() for _ in range(n)]  


def s_list(): return list(input())


def mi(n): return [wi() for _ in range(n)]  


def mip(n): return [wip() for _ in range(n)]


def ms(n): return [ws() for _ in range(n)]


def num_grid(n): return [[int(i) for i in sys.stdin.readline().split()[
    0]] for _ in range(n)]  


def grid(n): return [s_list() for _ in range(n)]


def main():
    K, N = wi()
    A = wi()
    for i in range(len(A)):
        if i == 0:
            ans = min(K-abs(A[i]+K-A[-1]), K - abs(A[i]-A[i+1]))
        elif i == N - 1:
            ans = min(ans, min(K-abs(K-A[i]+A[0]), K - abs(A[i]-A[i-1])))
        else:
            ans = min(ans, min(K-abs(A[i]-A[i+1]), K - abs(A[i]-A[i-1])))
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import math

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

res = n-1
top = (k - a[-1]) + a[0]
for i in range(n-1):
    if a[i+1] - a[i] > top:
        top = a[i+1] - a[i]
        res = i

print (k-top)