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:
# coding: utf-8
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)
#print (A)

p = [A[i+1] - A[i] for i in range(N) ]
#print (p)
p.sort()
print (K - p[-1])

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
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))  # 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(' ')))

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)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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
# fractions.gcd() を用いること
# math.log2()はatcoderでは対応していない．留意せよ．

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

#N軒目から1軒目までの距離が最大の時
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))

Submission status: Accepted

Solution code:

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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(distance)
#print(max(distance))
print(sum(distance) - max(distance))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
"""
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)
# import numpy as np

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


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


def ss(): return input()


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


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


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


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


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)]  # NumberGrid


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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def main():
  k, N = (int(x) for x in input().split())
  min_LIST = []
  LIST = []
  LIST = list(map(int,input().split()))
  x = 0

  for i in range(len(LIST) - 1):
    min_LIST.append(LIST[i + 1] - LIST[i])
    if(x <= min_LIST[i]):
      x = min_LIST[i]

  if(N != 2):
    min_LIST.append(LIST[0] + (k - LIST[-1]))
    if(x <= (LIST[0] + (k - LIST[-1]))):
      x = (LIST[0] + (k - LIST[-1]))

  sum_list = sum(min_LIST) - x

  print(sum_list)
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):
  if i!=0 and i!=n-1:
    B.append(min(k-(A[i]-A[i-1]),k-(A[i+1]-A[i])))
  elif i==0:
    B.append(min(k-(k-A[n-1]+A[0]),k-(A[i+1]-A[i])))
  elif i==n-1:
    B.append(min(k-(A[i]-A[i-1]),k-(A[0]+k-A[n-1])))
print(min(B))

Submission status: Accepted

Solution code:
def myAnswer(K:int,N:int,A:list) -> int:
   distance=[]
   pre = A.pop(0)
   MIN = pre
   for a in A:
      distance.append(a - pre)
      pre = a
   distance.append(MIN + K - A[-1])
   distance.sort()
   return sum(distance[:N - 1])

def modelAnswer():
   tmp=1
def main():
   K,N = map(int,input().split())
   A = list(map(int,input().split()))
   print(myAnswer(K,N,A[:]))


if __name__ == '__main__':
   main()

Submission status: Accepted

Solution code:
k, n = map(int, input().split())
housePosition = list(map(int, input().split()))
housePosition.append(k + housePosition[0])
biggestDistance = 0
for i in range(0, n):
  currentDistance = housePosition[i + 1] - housePosition[i]
  if(biggestDistance < currentDistance):
    biggestDistance = currentDistance
print(k - biggestDistance)

Submission status: Accepted

Solution code:
def main():

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

    mx = 0
    cnt = 0
    for i in range(1,n):
        tmp = a[i] - a[i - 1]
        if tmp > mx:
            mx = tmp
        cnt += tmp
    tmp = k - a[-1] + a[0]
    if tmp > mx :
        mx = tmp
    cnt = cnt + tmp - mx
    print(cnt)



if __name__ =='__main__':
    main()

Submission status: Accepted

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

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

dis.append(a[0]+k-a[n-1])
  
print(str(k-max(dis)))

Submission status: Accepted

Solution code:
a, b = map(int, input().split())
homes = input().split()
homes_number = [int(s) for s in homes]
long = []
for i in range(b-1):
    x = homes_number[i+1] - homes_number[i]
    long.append(x)
y = a - homes_number[b-1] + homes_number[0]
long.append(y)
print(a-max(long))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
k, n = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(lambda x: x + k, a))
a.extend(b)
min = float('inf')
for i in range(n):
    if a[i + n - 1] -  a[i] < min:
        min = a[i + n - 1] - a[i]
print(min)

Submission status: Accepted

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

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

print(k - max(t))

Submission status: Accepted

Solution code:
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):
	d = A[i + 1] - A[i]
	if max_d < d:
		max_d = d
print(K - max_d)

Submission status: Accepted

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

Submission status: Accepted

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

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

if(max < (a[0] + (k-a[n-1]))):
    max = (a[0] + (k-a[n-1]))

print(k-max)

Submission status: Accepted

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

x = k + A[0] - A[n-1]

for i in range(1,n):
    y = A[i]-A[i-1]
    if y > x:
        x = y

print(k-x)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
K, N = map(int, input().split())
A = list(map(int, input().split()))
maxDis = 0
for x in range(len(A)):
    if x != len(A) - 1:
        maxDis = max(maxDis, A[x + 1] - A[x])
    else:
        maxDis = max(maxDis, A[0] - A[x] + K)
print(K - maxDis)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
 
K, N, *A = map(int, read().split())
A.append(A[0] + K)
gap = max(y - x for x, y in zip(A, A[1:]))
print(K - gap)

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])))
index = li.index(max(li))
li.pop(index)
print(sum(li))

Submission status: Accepted

Solution code:
K, N = map(int, input().split())
A = list(map(int, input().split()))
 
A += [A[0] + K]
gap = max(y-x for x,y in zip(A, A[1:]))
print(K - gap)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
 
K, N, *A = map(int, read().split())
A += [A[0] + K]
gap = max(y-x for x,y in zip(A, A[1:]))
print(K - gap)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
 
K, N, *A = map(int, read().split())
 
max_distance = K + (A[0] - A[-1])
 
for i in range(1, N):
  max_distance = max(max_distance, A[i] - A[i - 1])
  
print(K - max_distance)

Submission status: Accepted

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

mi = min(a[n-1]-a[0], (k-a[1])+a[0])

for i in range(1,n-1):
  tmp = min(k-(a[i]-a[i-1]), k-(a[i+1]-a[i]))
  mi = min(tmp,mi)

print(mi)

Submission status: Accepted

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

if k - a[n-1] + a[0] > max:
    print(a[n-1] - a[0])
else:
    print(k - max)

Submission status: Accepted

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

a.append(a[0]+k)

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

print(k-dist)

Submission status: Accepted

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

#最大の距離を求める

for i in range(N):
  B[i] = min((A[i]-A[(i+1)%N])%K,(-A[i]+A[(i+1)%N])%K)
print(K-max(B))

Submission status: Accepted

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

x_list = A_list[:-1]

y_list = A_list[1:]

diff_list = list(map(lambda x,y: y - x, x_list, y_list))
diff_list.append(int(K-A_list[-1] + A_list[0]))

print(K - max(diff_list))

Submission status: Accepted

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

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

print(k - max_d)

Submission status: Accepted

Solution code:
p,q= input().split()
a,b =(int(p), int(q))
f = map(int,input().split())
f_list = list(f)
out_dis =f_list[0] + a -f_list[b-1]
dis_list=[out_dis]
for i in range(b-1):
    dis = f_list[i+1]-f_list[i]
    dis_list.append(dis)

print(int((sum(dis_list)-max(dis_list))))

Submission status: Accepted

Solution code:

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

x = max(l)
print(k-x)

Submission status: Accepted

Solution code:
k,n=map(int,input().split())
import numpy as np
l=list(map(int,input().split()))
l=np.array(l+[l[0]+k])
print(k-np.max(np.diff(l)))

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(N-1):
    ans = min(ans,K-(A[i+1]-A[i]))

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
K,n = map(int,input().split(' '))
A = list(map(int, input().split(' ')))
A.sort()
maxD = K-(A[-1]-A[0])
i = 0
while i < n-1:
    if A[i+1]-A[i] > maxD:
        maxD = A[i+1]-A[i]
    i += 1
print(K-maxD)

Submission status: Accepted

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

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

print(K-l)

Submission status: Accepted

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

    value_list = []
    value_list.append(K - ie_list[-1] + ie_list[0])
    count = 0
    while count != N - 1:
        value_list.append(ie_list[count + 1] - ie_list[count])
        count += 1
    print(K - max(value_list))

resolve()

Submission status: Accepted

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

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

Submission status: Accepted

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

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

# 最初と最後の家の距離（左側）を計算
distance_max = k - (A[-1]- A[0])

# 上記のdistanceより長い距離があるか調べる
for i in range(n-1):
    dis = A[i+1] - A[i]
    distance_max = max(distance_max, dis)

# 一番長い距離を切り、円環を切る
ans = k - distance_max
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

distence_list = [x for x in [ A[i+1] - A[i] for i in range(len(A)-1)]]

m = max(distence_list)

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

if m > x:
  print(K-m)
else:
  print(A[-1] - A[0])

Submission status: Accepted

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