Problem:


Score : 300 points

Problem Statement

There is a circular pond with a perimeter of K meters, and N houses around them.

The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.

When traveling between these houses, you can only go around the pond.

Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Constraints

2 \leq K \leq 10^6

2 \leq N \leq 2 \times 10^5

0 \leq A_1 < ... < A_N < K

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K N
A_1 A_2 ... A_N

Output

Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Sample Input 1

20 3
5 10 15

Sample Output 1

10

If you start at the 1-st house and go to the 2-nd and 3-rd houses in this order, the total distance traveled will be 10.

Sample Input 2

20 3
0 5 15

Sample Output 2

10

If you start at the 2-nd house and go to the 1-st and 3-rd houses in this order, the total distance traveled will be 10.



Sample input:
20 3
5 10 15


Sample output:
10

Submission status: Accepted

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

Submission status: Accepted

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

dist = [x[i] - x[i - 1] for i in range(1, n)]
dist.append(x[0] + k - x[n - 1])

# print(len(dist))
ans = k - max(dist)

print(ans)

Submission status: Accepted

Solution code:
# template by 3xC and starkizard.
# contributors: 

#####################################################################################
from __future__ import division, print_function 

import sys
import os
from collections import Counter, deque, defaultdict
import itertools
import math
import io


"""Uncomment modules according to your need"""


# from bisect import bisect_left, bisect_right, insort
# from heapq import heappop, heapify, heappush
# from random import randint as rn
# from Queue import Queue as Q
# from copy import deepcopy
# from decimal import *
# import re
# import operator

#####################################################################################
# this enables you to write python3 code with PyPy2 (Python 2)
if sys.version_info[0] < 3:
    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip

#####################################################################################

"""value of mod"""
MOD = 998244353
mod = 10**9 + 7

"""Uncomment next 4 lines if doing huge recursion"""
# import threading
# threading.stack_size(1<<27)
# sys.setrecursionlimit(10000

def prepare_factorial(mod=mod):
    """ returns two lists, factorial and inverse factorial modulo argument by default 10**9 +7 """
    # Comment code out when you don't need inverse factorial or vice versa
    fact = [1]
    for i in range(1, 200005):
        fact.append((fact[-1] * i) % mod)

    ifact = [0] * 200005
    ifact[200004] = pow(fact[200004], mod - 2, mod)
    for i in range(200004, 0, -1):
        ifact[i - 1] = (i * ifact[i]) % mod

    return fact, ifact

def modinv(n, p):
    """ returns N inverse modulo p """
    return pow(n, p - 2, p)

def ncr(n, r,  fact, ifact):
    """ takes 4 arguments: n , r and factorial and inverse factorial lists"""
    t = (fact[n] * (ifact[r]*ifact[n-r]) % MOD)% MOD
    return t


def get_n(Sum):    
    """this function returns the maximum n for which Summation(n) <= Sum"""
    ans = (-1 + sqrt(1 + 8*Sum))//2
    return ans

def sieve(n):
    """ returns a list of prime numbers till n """
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r



def divs(n, start=1):
    """ returns a list of all divisors till n """
    divisors = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if n % i == 0:
            if n / i == i:
                divisors.append(i)
            else:
                divisors.extend([i, n // i])
    return divisors



def divn(n, primes):
    """ returns the number of divisors, two arguments n and the sieve till n """
    divs_number = 1
    for i in primes:
        if n == 1:
            return divs_number
        t = 1
        while n % i == 0:
            t += 1
            n //= i
        divs_number *= t



def lrfind(d, x, default=-1):
    """ Takes 2 arguments an iterable and an element. returns a tuple (firstoccurence,lastoccurence) -1 if not found """
    left = right = -1
    for i in range(len(d)):
        if d[i] == x:
            if left == -1: left = i
            right = i
    if left == -1:
        return default, default
    else:
        return left, right

def gcd(x, y): # math.gcd is slower
    """ returns greatest common divisor of x and y """
    while y:
        x, y = y, x % y
    return x

def check_sorted(a):
    ''' returns True/False '''
    for i in range(len(a)-1):
        if a[i]>a[i+1]:
            return False
    return True
def ceil(n, k=1): return n // k + (n % k != 0) #returns math.ceil but protecting against floating inconsistencies
def input(): return sys.stdin.readline().strip()
def ii(): return int(input()) #inputs integer
def mi(): return map(int, input().split()) # inputting space seperated variables for example x,y,z
def li(): return list(map(int, input().split())) #inputting a space seperated list of integers
def lw(): return input().split() #inputting a space seperated list of strings
def lcm(a, b): return abs(a * b) // gcd(a, b) #returns LCM of two arguments
def prr(a, sep=' ', end='\n'): print(sep.join(map(str, a)), end=end) #For printing an iterable with seperator sep as optional second argument (default : " "), ending character (default: "\n") as optional third
def dd(): return defaultdict(int) #returns a dictionary with values defaulted to 0
def ddl(): return defaultdict(list) #returns a dictionary with values defaulted to []
def write(s): return sys.stdout.write(s)












###################################################################
def main():
    #CODE GOES HERE:
    k,n=mi()
    a=li()
    a.append(a[0])
    diff=[]
    for i in range(1,n+1):
        c=abs(a[i]-a[i-1])
        d=k-c
        diff.append(min(c,d))
    print(k-max(diff))









""" -------- Python 2 and 3 footer by Pajenegod and c1729 ---------"""

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192

class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO, self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill();
            self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.getvalue())
            self.truncate(0), self.seek(0)


class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            self.write = lambda s: self.buffer.write(s.encode('ascii'))
            self.read = lambda: self.buffer.read().decode('ascii')
            self.readline = lambda: self.buffer.readline().decode('ascii')


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')

""" main function"""

if __name__ == '__main__':
    main()
    # threading.Thread(target=main).start()

Submission status: Accepted

Solution code:
k,n = map(int, input().split())
A = list(map(int, input().split()))
B = []
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))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

li = []

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

print(sum(li)- max(li))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

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


print(sum(li) - max(li))

Submission status: Accepted

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

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

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

#print(li)

print(sum(li) - max(li))

Submission status: Accepted

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

for i in range(n):
  if counter < a[i+1]-a[i]:
    counter = a[i+1]-a[i]

print(min(k-counter,a[n-1]-a[0]))

Submission status: Accepted

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

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

As = sorted(A)
As.append(As[0]+K)

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

print(K-max(gap))

Submission status: Accepted

Solution code:
def resolve():
    K, N = map(int, input().split())
    A = list(map(int, input().split()))
    B = [max(A)-min(A)]
    for i in range(N-1):
        B.append(A[i+1]-A[i])
    for j in B:
        if j > K/2:
            B.remove(j)
            B.append(K-j)
    print(K-max(B))
resolve()

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
a = list(map(int,input().split()))
b = []
l = 0

for i in range(m):
    if l+2 <= m:
        b.append(int(abs(a[l] - a[l+1])))
        l += 1
    elif l+2>m:
        b.append(int(n-a[l]+a[0]))

b.pop(b.index(max(b)))
print(sum(b))

Submission status: Accepted

Solution code:
#!/usr/bin/python3
import sys
input = lambda: sys.stdin.readline().strip()
k, n = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
a.append(k + a[0])
S = sum(abs(a[i] - a[i - 1]) for i in range(1, len(a)))
print(min(S - abs(a[i] - a[i - 1]) for i in range(1, len(a))))

Submission status: Accepted

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

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

num = 0

for i in range(n):
    if num < abs(a[i] - a[i-1]):
        if not i:
            num = k - a[i-1] + a[i]
        else:
            num = a[i] - a[i-1]
        s = i
        e = i-1

if not s:
    print(a[e] - a[s])
else:
    print(k - a[s] + a[e])

Submission status: Accepted

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

print(k - max(B))

Submission status: Accepted

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

li = []

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

li.append(abs(a[0] + (k - a[-1])))
print(sum(li) - max(li))

Submission status: Accepted

Solution code:
# C - Traveling Salesman around Lake
K,N = map(int,input().split())
A = list(map(int,input().split()))
B = [0]*N
for i in range(N):
    B[i] = (A[(i+1)%N]-A[i])%K
x = max(B)
print(K-x)

Submission status: Accepted

Solution code:
K, N = map(int,input().split())
lis = list(map(int,input().split()))
l = []

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

l.append(lis[0] + (K-lis[-1]))
l.remove(max(l))
print(sum(l))

Submission status: Accepted

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

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

a.append(k + a[0])

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

m = max(b)

print(k-m)

Submission status: Accepted

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

maxDistance = 0
for k,v in enumerate(A) :
   maxDistance = max(maxDistance, K - A[k] + A[0]) if ( k >= len(A)-1 ) else max(maxDistance, A[k+1] - A[k]) 

print(K - maxDistance)

Submission status: Accepted

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

MaxD = (K-A[N-1])+A[0]
for T in range(0,N-1):
    Dist = A[T+1]-A[T]
    MaxD = max(MaxD,Dist)
print(K-MaxD)

Submission status: Accepted

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

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

b = sorted(b)
print(sum(b[:n-1]))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
k, n, *a = map(int, open(0).read().split())
a.append(k+a[0])
e = []
for i in range(n):
    e.append(a[i+1]-a[i])
print(sum(e)-max(e))

Submission status: Accepted

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

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

print(K-max(D))

Submission status: Accepted

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

Submission status: Accepted

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

d = [None] * n
sum = 0
for i in range(n):
    if i == n-1:
        d[n-1] = k - a[n-1] + a[0]
    else:
        d[i] = a[i+1] - a[i]
    sum += d[i]
print(sum - max(d))

Submission status: Accepted

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

d = [None] * n
sum = 0
for i in range(n):
    if i == n-1:
        d[n-1] = k - a[n-1] + a[0]
    else:
        d[i] = a[i+1] - a[i]
    sum += d[i]
ans = 2 * 10**11
for i in range(n):
    if sum - d[i] < ans:
        ans = sum - d[i]
print(ans)

Submission status: Accepted

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

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

m = max(d)
print(sum(d) - m)

Submission status: Accepted

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

Submission status: Accepted

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

#時計回り
D1 = []
for i in range(N-1):
  d = A[i+1] - A[i]
  if d < 0:
    d += K
  D1.append(d)
d = A[0] - A[-1]
if d < 0:
  d += K
D1.append(d)


#反時計回り
D2 = []
for i in range(N-1):
  d = A[i] - A[i+1]
  if d < 0:
    d += K
  D2.append(d)
d = A[-1] - A[0]
if d < 0:
  d += K
D2.append(d)

D1 = sorted(D1)
D2 = sorted(D2)

T1 = sum(D1[:-1])
T2 = sum(D2[:-1])

print(min([T1, T2]))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

d = (k - a[-1]) + a[0]
if d > d_max:
    d_max = d

print(k - d_max)

Submission status: Accepted

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

for i in range(n - 1):
    d = a[i + 1] - a[i]
    d_max = max(d_max, d)

d = (k - a[-1]) + a[0]
d_max = max(d_max, d)

print(k - d_max)

Submission status: Accepted

Solution code:
k, n = map(int, input().split())
a = list(map(int, input().split()))
d = [0] * n
d_max = 0

for i in range(n - 1):
    d[i] = a[i + 1] - a[i]
    d_max = max(d_max, d[i])

d[-1] = (k - a[-1]) + a[0]
d_max = max(d_max, d[-1])

print(k - d_max)

Submission status: Accepted

Solution code:
p,n=map(int,input().split())
l=list(map(int,input().split()))
s=0
l1=[]
for i in range(1,n):
    l1.append(l[i]-l[i-1])
    s+=l1[-1]
l1.append(p-s)
l1.remove(max(l1))
print(sum(l1))

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
lst = list(map(int,input().split()))
prev = 0
for i in range(m -1):
    m = abs(lst[i] - lst[i+1])
    if m > prev:
        prev = m
last = n - lst[-1] + lst[0]
k = max(prev, last)
print(n - k)

Submission status: Accepted

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

dis = 0

for i,j in zip(range(0,N),range(-1,N-1)):
    if i==0:
        temp = K-A[j]+A[i]
    else:
        temp = abs(A[i]-A[j])
    if temp > dis:
        dis = temp
print(K-dis)

Submission status: Accepted

Solution code:
import sys

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

def calcr(k, n, start, a):
    if start == 0:
        return a[n - 1] - a[0]
    else:
        return k - a[start] + a[start - 1]

def calcl(k, n, start, a):
    if start == n - 1:
        return a[n - 1] - a[0]
    return a[start] + k - a[start + 1]

mindist = calcr(k, n, 0, a)
for i in range(n):
    mindist = min(mindist, calcr(k, n, i, a))
    mindist = min(mindist, calcl(k, n, i, a))

print(mindist)

Submission status: Accepted

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

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

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

Submission status: Accepted

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

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

res = 10**14
for i in range(N, 2*N):
  res = min(res, cumsum[i]-cumsum[i-N+1])
print(res)

Submission status: Accepted

Solution code:
k,n=map(int,input().split())
a=list(map(int,input().split()))
b=k+1
for m in range(len(a)):
  a.append(a[m]-k)
a.sort()
for l in range(int(len(a)/2)):
  if b > -a[l]+a[n+l-1]:
    b=a[n+l-1]-a[l]
print(b)

Submission status: Accepted

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

dist = K-(A[N-1]-A[0])

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

print(abs(K-dist))

Submission status: Accepted

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

A = list(map(int, input().split()))
A.append(A[0] + k)
D = [A[i + 1] - A[i] for i in range(len(A) - 1)]
print(k - max(D))

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
result=[]
a=list(map(int,input().split()))
for i in range(m-1):
    r1=a[i+1]-a[i]
    result.append(r1)
r2=n-a[-1]+a[0]
result.append(r2)
print(n-max(result))

Submission status: Accepted

Solution code:
k,n=map(int,input().split())
house=list(map(int,input().split()))
dist=k-house[len(house)-1]+house[0]
for i in range(n-1):
    new_dist=house[i+1]-house[i]
    if dist<=new_dist:
        dist=new_dist
dist=k-dist
print(dist)

Submission status: Accepted

Solution code:
import numpy as np
K, N = map(int, input().split())

route = list(map(int, input().split()))
diff = np.diff(np.array(route)).tolist()
diff.append(route[0]+K-route[-1])
diff.remove(max(diff))
print(sum(diff))

Submission status: Accepted

Solution code:
X = input().split()

K = int(X[0])
N = int(X[1])

A = input().split()

i = 0
j = 1
max_distance = 0

while j < N:
    a = int(A[j-1])
    b = int(A[j])
    distance = b - a
    if distance > max_distance:
        max_distance = distance
    j += 1

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

if last_distance > max_distance:
    max_distance = last_distance

shortest_distance = K - max_distance
print(shortest_distance)

Submission status: Accepted

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

    
print(K-max(l))

Submission status: Accepted

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

acc = arr[0] + k-arr[-1]
for i in range(n-1):
    acc = max(acc, arr[i+1] - arr[i])

print(k-acc)

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

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

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

gap.append(k-a[-1])
m = max(max(gap),gap[0]+gap[-1])
print(k-m)

Submission status: Accepted

Solution code:
#import bisect,collections,copy,heapq,itertools,math,numpy,string
#from operator import itemgetter
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
K,N = LI()
A = LI()
path_len = [0] * N
maxpath_ind = 0
maxpath_num = 0

# i -> i+1 への距離をiに保存
for i in range(N):
  if i+1==N:
    tmp = K-A[i]+A[0]
  else:
    tmp = A[i+1] - A[i]
  path_len[i] = tmp
  if tmp > maxpath_num:
    maxpath_num = tmp
    maxpath_ind = i

sum = 0
for i in range(N):
  if i != maxpath_ind:
    sum+=path_len[i]

print(sum)

Submission status: Accepted

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

Submission status: Accepted

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

max_d = 0
for i in range(n):
    if i == 0:
        d = A[i] + (k - A[-1])
    else:
        d = A[i] - A[i-1]

    if d > max_d:
        max_d = d

print(k-max_d)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
k,n=map(int,input().split())
arr=list(map(int,input().split()))
ans=10**18 #最小値を求めるので十分大きな値で初期化
for i in range(n): #上式を元に最短距離を求める
 dist1=(arr[i-1]-arr[i])%k
#  n個中のiの次最高びになると0番目に戻る
 dist2=(arr[i]-arr[(i+1)%n])%k
 ans=min(ans,dist1,dist2)#dist1と2の小さい方をansとする
print(ans)

Submission status: Accepted

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

distanceList = []

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

for i in range(len(M) - 1):
    distanceList.append(M[i + 1] - M[i])

print(N[0] - max(distanceList))

Submission status: Accepted

Solution code:
K, N = map(int,input().split())
An = list(map(int, input().split()))
maxi = 0
for i in range(N):
    if i == N-1:
        i = -1
        if K + (An[i + 1] - An[i]) > maxi:
            maxi = K + (An[i + 1] - An[i])
            break
    if An[i+1] - An[i] > maxi:
        maxi = An[i+1] - An[i]
print(K - maxi)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
K,N=map(int,input().split())
Alist=list(map(int,input().split()))
kyori=[]
ans=0
for i in range(N-1):
    kyori.append(Alist[i+1]-Alist[i])
kyori.append(K-Alist[N-1]+Alist[0])
kyori.remove(max(kyori))
for i in range(len(kyori)):
    ans+=kyori[i]
print(ans)

Submission status: Accepted

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

lis = []

for i in range(n-1):
    lis.append(a[i+1] - a[i])
lis.append(k- a[-1] + a[0])
print(k-max(lis))

Submission status: Accepted

Solution code:
k,n=map(int,input().split())
ai=list(map(int,input().split()))
res = []
for i in range(n-1):
  res.append(ai[i+1]-ai[i])
res.append(k-ai[n-1]+ai[0])
mv = max(res)
res.remove(mv)
print(sum(res))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
k, n = map(int,input().split())
p = list(map(int, input().split()))
l = []

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

Submission status: Accepted

Solution code:
a,b=map(int,input().split())
S=list()
L=list(map(int,input().split()))
for i in range(1,b):
  S.append(L[i]-L[i-1])
S.append(a+L[0]-L[-1])
print(a-max(S))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
K, N = map(int, input().split(' '))
A_n = list(map(int, input().split(' ')))
tmp = A_n[0] + K - A_n[-1]
for i in range(1, len(A_n)):
    if abs(A_n[i] - A_n[i-1]) > tmp:
        tmp = abs(A_n[i] - A_n[i-1])
print(K-tmp)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(K: int, N: int, A: "List[int]"):
    r = -1
    for i in (range(len(A))):
        if i == 0:
            tmp = A[i] + (K - A[len(A)-1])
        else:
            tmp = A[i] - A[i-1]
        r = max(tmp, r)
    print(K-r)


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    K = int(next(tokens))  # type: int
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(K, N, A)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

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

    print(sum(dist)-max(dist))
    return


resolve()

Submission status: Accepted

Solution code:
N,X=map(int,input().split())
S=list(map(int,input().split()))

uramichi=N-S[X-1]+S[0]
saidai=0
L=[]

goukei=0

for i in range(0,X-1):
    if saidai<S[i+1]-S[i]:
        saidai=S[i+1]-S[i]
    goukei+=S[i+1]-S[i]

if saidai>uramichi:
    goukei=goukei-saidai+uramichi
    
print(goukei)

Submission status: Accepted

Solution code:
K, N = map(int, input().split())
loc = list(map(int, input().split()))
distances = []
total = []

for i in range(N-1):
    distances.append(loc[i+1] - loc[i])

distances.append(loc[0] + K - loc[N-1])
max_dis = max(distances)

print(K - max_dis)

Submission status: Accepted

Solution code:
K, N = map(int, input().split())
loc = list(map(int, input().split()))
distances = []
total = []

for i in range(N-1):
    distances.append(loc[i+1] - loc[i])

distances.append(loc[0] + K - loc[N-1])

for i in range(N):
    total.append(K - distances[i])

print(min(total))

Submission status: Accepted

Solution code:
# input
k, n = map(int, input().split())
house = [int(i) for i in input().split()]
house.append(k+house[0])
dist = []
cand = []

# main
for i in range(n):
  dist.append(house[i+1]-house[i])
  
for i in range(n):
  cand.append(k-dist[i])

# output
print(min(cand))

Submission status: Accepted

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

Submission status: Accepted

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

li = []
for i in range(n - 1):
    li.append(A[i + 1] - A[i])
li.append(A[0] + k - A[n - 1])
print(k - max(li))

Submission status: Accepted

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

print(k-res)