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:
k,n=map(int,input().split())
a=list(map(int,input().split()))
a=a+[k+a[0]]
b=[a[i+1]-a[i] for i in range(n)]
m=max(b)
print(k-m)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:

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

n_prev= a[n-1]-k

m=0

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

print(res)

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

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

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


l = 0
l_min = float('inf')

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

Submission status: Accepted

Solution code:
from collections import deque

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

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

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

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

print(k - max(bet))

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys


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


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

    max_distance = 0

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

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

    distance = first_a + (k - last_a)

    if max_distance <= distance:
        # 時計回りで計算
        move_distance = last_a - first_a
    else:
        # 反時計回りで計算
        move_distance = a_list[max_address_1] + (k - a_list[max_address_2])

    print(move_distance)




if __name__ == "__main__":
    resolve()

Submission status: Accepted

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

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

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

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

print(sum(dlst))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys
import math


debug = False

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

def parse_input(lines_as_string = None):

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

    return (k, n, a)


def solve(k, n, a):


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


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

if __name__ == '__main__':

    main()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# Author: cr4zjh0bp
# Created: Sat Mar 28 11:53:27 UTC 2020
import sys
 
stdin = sys.stdin
inf = 1 << 60
mod = 1000000007
 
ni      = lambda: int(ns())
nin     = lambda y: [ni() for _ in range(y)]
na      = lambda: list(map(int, stdin.readline().split()))
nan     = lambda y: [na() for _ in range(y)]
nf      = lambda: float(ns())
nfn     = lambda y: [nf() for _ in range(y)]
nfa     = lambda: list(map(float, stdin.readline().split()))
nfan    = lambda y: [nfa() for _ in range(y)]
ns      = lambda: stdin.readline().rstrip()
nsn     = lambda y: [ns() for _ in range(y)]
ncl     = lambda y: [list(ns()) for _ in range(y)]
nas     = lambda: stdin.readline().split()

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

ans = inf

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

# if lst[-1] != k:
#     lstap = lst.append(k)
# An < kだからいらない
wmax = 0

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

judge = [lst[0] + k - lst[-1], wmax]
# print(judge)
print(k - max(judge))

# if k - lst[-1] <= lst[0]:
#     print(lst[-1] - lst[0])

# elif k - lst[-1] > lst[0]:
#     print

# # elif k - lst[-1] < lst[0]:
# #     lst[-1] -

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

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

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

Submission status: Accepted

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

print(k-d)

Submission status: Accepted

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

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

print(k-m)

Submission status: Accepted

Solution code:
import copy

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

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

print(route)

Submission status: Accepted

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

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

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

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

print(min(d_left, d_right))

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

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

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

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

print(k - max(d))

Submission status: Accepted

Solution code:
from collections import deque
import heapq
import itertools
import math

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

print(k-max_root)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
#スペース区切りの整数の入力
K, N = map(int, input().split())
#文字列の入力
A = input()
#コンマで区切る
A_list = A.split(' ')
for i in range(len(A_list)):
    A_list[i] = int(A_list[i])

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

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

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

max_ = max(aida_list)

#print("aida",aida_list)
aida_list.remove(max_)

ans = sum(aida_list)

#print("A",A_list)
#print(aida_list)
print(ans)

Submission status: Accepted

Solution code:
import sys
# sys.stdin = open('input.txt')

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

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

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

print(min(left, right))

Submission status: Accepted

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

print(k-max(dislis))

Submission status: Accepted

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

maxi = 0

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

    maxi = max(maxi, x)

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

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

maxi = max(maxi, x)

print(k - maxi)

Submission status: Accepted

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

print(K-max)

Submission status: Accepted

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

diff = 0
largest_diff = 0
sumNum = 0 

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

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

print(sumNum-largest_diff)

Submission status: Accepted

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

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

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

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

print(ans)

Submission status: Accepted

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

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

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







    return 0


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python

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

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

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

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

Submission status: Accepted

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

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

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

#import pdb; pdb.set_trace()
Sum = 0
n = N -1
for x in range(N):
  if x == n:
    Sum += (K - a[n]) + a[0]
  else:
    Sum += a[x+1] - a[x]

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

l = max(ans)

min_road = Sum - l
print(min_road)

Submission status: Accepted

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

max = 0

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

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


dist = k - max
print(dist)

Submission status: Accepted

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

Submission status: Accepted

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

print(ans-mx)

Submission status: Accepted

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

Submission status: Accepted

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

diff = [0] * N
for x in range(N):
    if x + 1 >= N:
        x -= N
    if A[x + 1] < A[x]:
        a = A[x + 1] + K
    else:
        a = A[x + 1]
    diff[x] = a - A[x]

ans = 0
temp = 0
for x in range(N - 1):
    ans += diff[x]
    temp += diff[x]

for x in range(N):
    idx = x + N - 1
    if idx >= N:
        idx -= N
        
    temp = (temp - diff[x] + diff[idx])
    if ans > temp:
        ans = temp
print(ans)

Submission status: Accepted

Solution code:
k,n=map(int,input().split())
a=list(map(int,input().split()))
ans=10**9
for i in range(n):
    bef=i-1
    af=i+1
    aa=0
    bb=0
    if bef<0:
        aa=a[-1]-a[0]
    else:
        aa=k-(a[i]-a[bef])
    if n-1<af:
        bb=a[-1]-a[0]
    else:
        bb=a[i]+abs(k-a[af])
    if aa<ans:
        ans=aa
    if bb<ans:
        ans=bb
print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
S = input().split()
K = int(S[0])
N = int(S[1])
A = []
B = []
a = input().split()
for o in range(N):
    A.append(int(a[o]))
A.sort()
for j in range(N-1):
    B.append(A[j+1] - A[j])
B.append(A[0] + K-A[N-1])
B.sort()
ans = 0
ans = K - B[N-1]

print(int(ans))

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,len(a)-1):
  l.append(a[i+1]-a[i])
print(k-max(l))

Submission status: Accepted

Solution code:
k,n = map(int,input().split())
n_inf = list(map(int,input().split()))
#n_inf.append(k)
#n_inf.insert(0,0)
kyori_list = [j for j in range(n-1)]
for i in range(n-1):
  kyori_list[i] = n_inf[i+1]-n_inf[i]
#print(kyori_list)
kyori_list.append((n_inf[0])+(k-n_inf[n-1]))
#print(kyori_list)
kyori_list.sort(reverse=1)
print(sum(kyori_list[1:n+1]))

Submission status: Accepted

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

for i in range(n):
  x = abs(a[i] - a[i-1])
  if x > k/2:
    x = abs(x - k) 
  d.append(x)

print(sum(d)-max(d))

Submission status: Accepted

Solution code:
K,N=list(int(i) for i in input().split())
A=list(int(i) for i in input().split())
ans=10**20
for i in range(N):
    if i>0 and i<N-1:
        ans=min(K-(A[i]-A[i-1]),ans,K-(A[i+1]-A[i]))
    elif i==0:
        ans=min(A[-1]-A[0],ans,K-(A[1]-A[0]))
    else:
        ans=min(A[-1]-A[0],K-(A[i]-A[i-1]),ans)
print(ans)

Submission status: Accepted

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

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

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

print(k - dd)

Submission status: Accepted

Solution code:
import copy
K,N = (int(x) for x in input().split())
a = list(map(int,input().split()))
b = copy.copy(a)
tmp = a[N-1]
for i in range(N-1):
  a[i+1] -= a[i]
a[0] += K-tmp
d1 = sum(a)-max(a)
b = b[::-1]
tmp =b[0] 
for i in range(N-1):
  b[i] -= b[i+1] 
b[N-1] += K-tmp
d2 = sum(b)-max(b)
print(min(d1,d2))

Submission status: Accepted

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

for i in range(len(A)-1):
    length = A[i+1] - A[i]
    length_list.append(length)
last = K - sum(length_list)
length_list.append(last)

ans = K - max(length_list)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
"""
"""


def int_as_array(num): return list(map(int, [y for y in str(num)]))


def array_as_int(arr): return int(''.join(map(str, arr)))


def read_int(): return int(input())


def read_array(): return list(map(int, input().split(' ')))


def array_to_string(arr, sep=' '): return sep.join(map(str, arr))


def matrix_to_string(arr, sep=' '): return '[\n' + '\n'.join(
    [sep.join(map(str, row)) for row in arr]) + '\n]'


def read(): input()


def solve(array, dist):
    total = 0
    biggest = 0
    for i, x in enumerate(array):
        if i == len(array) - 1:
            next_pos = dist + array[0]
        else:
            next_pos = array[i + 1]
        d = next_pos - array[i]
        if d > biggest:
            biggest = d
        total += d
    return total - biggest


K, N = read_array()
array = read_array()
print(solve(array, K))

Submission status: Accepted

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

Submission status: Accepted

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

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

int(K)
int(N)

#Bは各距離とする
B = []
for i in range(0, len(A)-1):
    B.insert(i,A[i+1]-A[i])
B.insert(int(N)-1,int(K)-A[int(N)-1]+A[0])

ans = 0

for j in range(int(N)):
    ans += B[j]

ans -= max(B)

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env pypy3
import sys
sys.setrecursionlimit(15000)
k,n = map(int,input().split())
a = list(map(int,input().split()))
d = [a[i]-a[i-1] for i in range(1,n)]+[a[0]+k-a[-1]]
#print(d)
m = max(d)
s = sum(d)
print(s-m)

Submission status: Accepted

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

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

distance.remove(max(distance))
print(sum(distance))

Submission status: Accepted

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

# tmp1 = A[-1] - A[0]
# tmp2 = A[-1] - (20 - A[0] - A[-1])
# tmp2 = A[-1] - A[1]

# print(min(tmp1, tmp2))
# # print(A[-1]-A[0])

# ans = []
ans = -1
for i in range(N):
    # 右方向
    tmp = A[-1] - A[i]
    if i != 0:
        tmp += K - A[-1] + A[i-1]
    
    if ans == -1:
        ans = tmp
    elif ans > tmp:
        ans = tmp
print(ans)

Submission status: Accepted

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

# a = []
ans = []
le = 0
a = list(map(int, input().split()))

# for i in range(n):
# a.append(input())

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

mx = numpy.argmax(ans)

for i in range(n):
    if i != mx:
        le = le + ans[i]


print(le)

Submission status: Accepted

Solution code:
def resolve():
    K, N = map(int, input().split())
    A = tuple(map(int, input().split()))
    diff_max = 0
    A_sum = 0

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

        diff_max = max(diff_max, diff)
        A_sum += diff

    print(A_sum - diff_max)
    
if __name__ == '__main__':
    resolve()

Submission status: Accepted

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

K = KN[0]
N = KN[1]

kyori = []

#家と家の間の距離を計算(1番目~2番目、2番目~3番目...)
for i in range(N-1):
    kyori.append(A[i+1] - A[i])
kyori.append(A[0]+K-A[N-1])

print(K - max(kyori))

Submission status: Accepted

Solution code:
import numpy as np

K,N=map(int,input().split())
A=np.zeros(N)
A=list(map(int, input().split()))
dif=np.zeros(N)

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

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

print(int(K-np.max(dif)))

Submission status: Accepted

Solution code:
import sys
import numpy as np
import itertools
from collections import deque

sys.setrecursionlimit(10**6)
readline = sys.stdin.readline

# input
K, N = [int(i) for i in readline().split()]
A = list(map(int, readline().split()))

A.append(A[0] + K)
tmp = np.diff(np.array(A))
distance = np.append(tmp, tmp[0:N-2])

#print(distance)

base = np.sum(distance[0:N-1])
ans = min(base, 1000000)
for i in range(N-1):
    #print(base)
    base -= distance[i]
    base += distance[N-1+i]
    ans = min(base, ans)
   
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
# int(input()) # 入力が1つ
k, n = map(int, input().split()) # 入力が複数
houses = list(input().split())
houses = [int(h) for h in houses]
houses.sort()
max_dist = 0
total = 0
for i in range(n):
    if i == n - 1:
        d = abs(k - houses[i] + houses[0])
    else:
        d = houses[i + 1] - houses[i]
    max_dist = max(max_dist, d)
    total += d

ans = total - max_dist
print(ans)

Submission status: Accepted

Solution code:
K, N = map(int, input().split())
A = list(map(int, input().split()))
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])
B_max = max(B)
print(K - B_max)

Submission status: Accepted

Solution code:
if __name__ == "__main__":
    k, n = map(int, input().split())
    a = list(map(int, input().split()))
    import numpy as np
    a = np.array(a)

    sa_kouho = a[0] + (k - a[-1])

    sa = a[1:] - a[0: -1]

    sa_kouho1 = max(sa)

    print(k - max(sa_kouho, sa_kouho1))

Submission status: Accepted

Solution code:
K, N = map(int, input().split())
A = list(map(int, input().split()))
cnt = 1
a = 0
B = []
if (max(A)-min(A)) <= K//2:
    print(max(A)-min(A))
else:
    for i in A:
        if i/cnt == K/N:
            a += 1
        cnt += 1
    
    if a == N:
        print(max(A)-min(A))
    else:
        for j in range(N):
            if j == N-1:
                haba = K-(A[j]-A[0])
            else:
                haba = A[j+1]-A[j]
            B.append(haba)
        print(K-max(B))

Submission status: Accepted

Solution code:
def main():
    k, n = map(int, input().split())
    num_list = list(map(int, input().split()))

    num_list.append(k+num_list[0])

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

    print(k-tmp)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import itertools
from collections import deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush,heapify
from fractions import gcd
from copy import deepcopy
import math
import queue
import numpy as np
#import sympy as syp(素因数分解とか)
Mod = 1000000007
import sys
sys.setrecursionlimit(100000) 
  
def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))+1):
        if prime[i] == 1:
            for j in range(2*i,n+1):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n+1):
        if prime[i] == 1:
            res.append(i)
    return res

 
class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py
 
    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)

def main(): #startline-------------------------------------------
    k,n = map(int,input().split())
    a = list(map(int,input().split()))
    anslist = []
    a.append(k+a[0])
    for i in range(n):
        anslist.append(abs(a[i+1]-a[i]))
    print(k-max(anslist))
if __name__ == "__main__":
    main() #endline===============================================

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

#num = B.index(max(B))
print(K - max(B))

Submission status: Accepted

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

A = list(map(int, input().split()))
a = A[-1] - A[0]
ans = 10000000
i = 1
for d in A:
  b = K-A[-i]+A[-i-1]
  ans = min(b, ans)
  i += 1
  if i == len(A):
    break

if a <= ans:
  print(a)
else:
  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):
  if i != n-1:
    d.append(abs(a[i+1] - a[i]))
  else:
    d.append(abs(k - a[n-1] + a[0]))
d_max = max(d)

print(k - d_max)