ManavSinghal157/NoFunEval huggingface dataset:
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 2432 ms):
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline

#a,b,c,d = map(int,readline().split())
s,k = readline().split()


a = [len(i) for i in s.split("0")]
while a and a[-1] == 0: a.pop()

if not a:
    print((1))
    exit()

MOD = 998244353

M = sum(a)+1
k = min(int(k),M)


dp = [[0]*M for _ in range(k+1)] # j 使って（上限 k）、l 余ってる
dp[0][0] = 1

#print(a)
for ai in a[::-1]:
    ndp = [[0]*M for _ in range(k+1)] # j 使って（上限 k）、l 余ってる
    for j in range(k+1):
        for l in range(M):
            for ll in range(l):
                ndp[j][ll] += dp[j][l]
                ndp[j][ll] %= MOD
            
            V = min(M-l,k-j+1,ai+1)
            for i in range(V):
                #if j+i > k: break
                ndp[j+i][l+i] += dp[j][l]
                ndp[j+i][l+i] %= MOD
    
    dp = ndp
    #print(dp)

ans = 0
for jj in range(k+1):
    ans += dp[jj][0]

print((ans%MOD))







Optimized program (CPU time: 323 ms):
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline

#a,b,c,d = map(int,readline().split())
s,k = readline().split()


a = [len(i) for i in s.split("0")]
while a and a[-1] == 0: a.pop()

if not a:
    print((1))
    exit()

MOD = 998244353

M = sum(a)+1
k = min(int(k),M)


dp = [[0]*M for _ in range(k+1)] # j 使って（上限 k）、l 余ってる
dp[0][0] = 1

#print(a)
for ai in a[::-1]:
    ndp = [[0]*M for _ in range(k+1)] # j 使って（上限 k）、l 余ってる
    for j in range(k+1):
        for l in range(M):
            if dp[j][l]:
                for ll in range(l):
                    ndp[j][ll] += dp[j][l]
                    ndp[j][ll] %= MOD

                V = min(M-l,k-j+1,ai+1)
                for i in range(V):
                    #if j+i > k: break
                    ndp[j+i][l+i] += dp[j][l]
                    ndp[j+i][l+i] %= MOD
    
    dp = ndp
    #print(dp)

ans = 0
for jj in range(k+1):
    ans += dp[jj][0]

print((ans%MOD))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 821 ms):
import numpy as np
# 締切が早いものから処理
N = int(eval(input()))
AB = np.array([[int(x) for x in input().split()] for _ in range(N)])
A = AB[:,0]
B = AB[:,1]
idx = B.argsort()
A = A[idx]
B = B[idx]
np.cumsum(A, out = A)
bl = (A <= B).all()
answer = 'Yes' if bl else 'No'
print(answer)


Optimized program (CPU time: 719 ms):
def main():
    N = int(eval(input()))
    A = []
    for _ in range(N):
        a, b = list(map(int, input().split()))
        A.append((a, b))

    A = sorted(A, key=lambda x: x[1])
    time = 0
    for a, b in A:
        time += a
        if time > b:
            return 'No'

    return 'Yes'

if __name__ == '__main__':
    print((main()))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 150 ms):
import numpy as np

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

alice_point = 0
bob_point = 0
for i in range(n):
    argmax_a = np.argmax(a_list)
    max_a = np.max(a_list)
    if i % 2 == 0: # If Alice takes a card
        alice_point += max_a
    else: # If Bob takes a card
        bob_point += max_a
    del a_list[argmax_a] # No confidence -> Review how to delete list element!

print((alice_point - bob_point))

Optimized program (CPU time: 18 ms):
n = int(eval(input()))
a_list = list(map(int, input().split()))
a_list = sorted(a_list, reverse=True)

alice_point = 0
bob_point = 0
for i in range(n):
    if i % 2 == 0:
        alice_point += a_list[i]
    else:
        bob_point += a_list[i]

print((alice_point - bob_point))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 73 ms):
from functools import reduce
N = int(eval(input()))

prime_table = [1] * (N+1)

for x in range(2, N+1):
    for t in range(2, x+1):
        while x % t == 0:
            prime_table[t] += 1
            x //= t
print((reduce(lambda x, y: x * y % (int(1e9) + 7), prime_table)))

Optimized program (CPU time: 18 ms):
def prime_factorize(n):
    while n % 2 == 0:
        a[2] += 1
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            a[f] += 1
            n //= f
        else:
            f += 2
    if n != 1:
        a[n] += 1

N = int(eval(input()))
a = [0]*(N+1)
for i in range(2, N+1):
    prime_factorize(i)
ans = 1
for i in a:
    if i > 0:
        ans *= (i+1)
big = 10**9 + 7
print((ans % big))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 320 ms):
import sys
sys.setrecursionlimit(10 ** 6)


def solve():
    S = (input())
    # print(S, len(S))

    words = {0: "dream", 1: "dreamer", 2: "erase", 3: "eraser"}

    TABLE = [[-1 for x in range(len(S) + 1)] for y in range(len(words) + 1)]

    def recur(i, w):
        if not TABLE[w][i] == -1:
            return TABLE[w][i]

        if i >= len(S):
            # print("jey", log)
            return True

        r1, r2, r3, r4 = False, False, False, False
        if S[i:i + 5] == words[0]:
            r1 = recur(i + 5, 0)
        if S[i:i + 7] == words[1]:
            r2 = recur(i + 7, 1)
        if S[i:i + 5] == words[2]:
            r3 = recur(i + 5, 2)
        if S[i:i + 6] == words[3]:
            r4 = recur(i + 6, 3)

        TABLE[w][i] = r1 or r2 or r3 or r4 or False

        return TABLE[w][i]

    ans = recur(0, 0)

    return ans


if __name__ == '__main__':
    res = solve()
    if res:
        print("YES")
    else:
        print("NO")


Optimized program (CPU time: 262 ms):
import sys
sys.setrecursionlimit(10 ** 6)

def solve():
    S = (input())
    # print(S, len(S))

    S = S[::-1]
    words = ("dream"[::-1], "dreamer"[::-1], "erase"[::-1], "eraser"[::-1])

    def recur(i):
        if i >= len(S):
            return True

        for word in words:
            if S[i:i + len(word)] == word:
                if recur(i + len(word)):
                    return True
        return False

    ans = recur(0)

    return ans


if __name__ == '__main__':
    res = solve()
    if res:
        print("YES")
    else:
        print("NO")
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 148 ms):
import numpy as np

eval(input())
A = np.array(list(map(int, input().split())))

ans = 0
while(all(A%2==0)):
    A = A/2
    ans += 1

print(ans)


Optimized program (CPU time: 19 ms):
eval(input())
A = list(map(int, input().split()))

ans = 0
while all(a%2==0 for a in A):
    A=[a/2 for a in A]
    ans += 1

print(ans)
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 124 ms):
import numpy as np
s = np.array(list((input())))
t = np.array(list((input())))
print((len(s[s==t])))


Optimized program (CPU time: 29 ms):
s = (input())
t = (input())
ans = 0
for i in range(len(s)):
    if s[i] == t[i]:
        ans += 1
print(ans)
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 118 ms):
import numpy as np
N=int(eval(input()))
print((2**int(np.log2(N))))

Optimized program (CPU time: 28 ms):
import math
N=int(eval(input()))
print((2**int(math.log2(N))))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 374 ms):
import numpy as np
mod=10**9+7
d=np.zeros(100100,dtype=np.int64)
d[0]=1
for i in range(1,10**5+1):
  d[i]=d[i-1]*i%mod
print((d[int(eval(input()))]))

Optimized program (CPU time: 55 ms):
d,mod=[1]+[0]*100100,10**9+7
for i in range(1,10**5+1):d[i]=d[i-1]*i%mod
print((d[int(eval(input()))]))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 1727 ms):
INF = 10**10

N, M = list(map(int, input().split()))
costs = []
keys = []
for _ in range(M):
    A, B = list(map(int, input().split()))
    cs = list(map(int, input().split()))
    costs.append(A)
    # 鍵を2進数化する
    key = 0
    for c in cs:
        key |= 1<<(c-1)
    keys.append(key)

# [1]の個数で分類する
maskss = [[] for _ in range(N+1)]
num1s = [0] * (2**N)
for S in range(2**N):
    num = bin(S).count('1')
    maskss[num].append(S)
    num1s[S] = num

dpAll = [INF] * (2**N)
for S in range(2**N):
    for cost, key in zip(costs, keys):
        if S & key == S:
            if cost < dpAll[S]:
                dpAll[S] = cost

dp = [INF] * (2**N)
for S in range(2**N):
    cost = dpAll[S]
    num1 = num1s[S]
    for k in range(1, (num1+1)//2+1):
        for mask in maskss[k]:
            if mask & S == mask:
                m2 = S^mask
                c2 = dp[mask] + dp[m2]
                if c2 < cost:
                    cost = c2
    dp[S] = cost

if dp[2**N-1] == INF:
    print((-1))
else:
    print((dp[2**N-1]))


Optimized program (CPU time: 694 ms):
import sys
input = sys.stdin.readline

def solve():
    INF = 10**10

    N, M = list(map(int, input().split()))
    keys = []
    costs = []
    for _ in range(M):
        a, b = list(map(int, input().split()))
        costs.append(a)
        cs = list(map(int, input().split()))
        key = 0
        for c in cs:
            key |= 1<<(c-1)
        keys.append(key)

    dp = [INF] * (1<<N)
    dp[0] = 0
    for S in range(1<<N):
        for key, cost in zip(keys, costs):
            S2 = S | key
            c2 = dp[S] + cost
            if c2 < dp[S2]:
                dp[S2] = c2

    if dp[-1] == INF:
        print((-1))
    else:
        print((dp[-1]))


solve()
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 299 ms):
from collections import Counter
import numpy as np

N = int(eval(input()))
A = np.array(input().split(), dtype = np.int64)

c = Counter(A.cumsum())
c[0] += 1
answer = sum(x*(x-1)//2 for x in list(c.values()))
print(answer)


Optimized program (CPU time: 187 ms):
N = int(eval(input()))
A = list(map(int,input().split()))
csum = [0]
temp = 0
for a in A:
    temp += a
    csum.append(temp)
# csum.sort()
# print(csum)
from collections import Counter
freq = Counter(csum)
ans = 0
for v in list(freq.values()):
    ans += (v*(v-1))//2
print(ans)
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 863 ms):
def mi():return list(map(int,input().split()))
import numpy as np
A,B,M=mi()
a=np.array(list(mi()))
b=np.array(list(mi()))
minab=min(a)+min(b)

ans=float("inf")

for i in range(M):
    x,y,c=mi()
    tmp=a[x-1]+b[y-1]-c
    ans=min(ans,tmp)
print((min(ans,minab)))


Optimized program (CPU time: 430 ms):
def mi():return list(map(int,input().split()))
A,B,M=mi()
a=list(mi())
b=list(mi())
ans=min(a)+min(b)
for _ in range(M):
    x,y,c=mi()
    ans=min(ans,a[x-1]+b[y-1]-c)
print(ans)
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 201 ms):
n_str = eval(input())
n_int = int(n_str)
# 1 ~ 50000
# 桁数が奇数= 1桁, 3桁, 5桁
# 1 ~ 9, 100 ~ 999,10000 ~ 99999の90909個しかないので全探索いけるか?
exs_list = []
for i in range(1, 100000):
    if len(str(i)) % 2 == 1:
        exs_list.append(i)

exs = {i: i for i in exs_list}

n_s = []
ans = 0
for i in range(1, n_int + 1):
    if len(str(i)) % 2 == 0:
        continue
    if i in exs:
        ans += 1

print(ans)







Optimized program (CPU time: 89 ms):
def digit_sum(n):
    # 各桁の和を求める
    # 計算量: O(logN)
    ans = 0
    while n > 0:
        ans += 1
        n //= 10
    return ans

n = int(eval(input()))
cnt = 0

for i in range(1, n+1):
    cnt += digit_sum(i) % 2

print(cnt)
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 80 ms):
"""Minimum cost Sort."""

def min_cost_sort(A):
    """Sort list A in ascending order.
 
    And return the switching cost in sorting.
    """
    B = list(A)
    B.sort()
    cost = 0
    min_w = B[0]
    for i, b in enumerate(B):
        tmp_cost = 0
        bi = A.index(b)
        n = 1
        while bi != i:
            n += 1
            st = B[bi]
            si = A.index(st)
            tmp_cost += b + st
            A[bi], A[si] = st, b
            bi = si
        dec = (n - 1) * (b - min_w)
        inc = 2 * (min_w + b)
        if dec < inc:
            cost += tmp_cost
        else:
            cost += tmp_cost - dec + inc
    return cost


n = eval(input())

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

ans = min_cost_sort(A)

print(ans)

Optimized program (CPU time: 60 ms):
"""Minimum cost Sort."""

def min_cost_sort(A):
    """Sort list A in ascending order.
 
    And return the switching cost in sorting.
    """
    B = list(A)
    B.sort()
    cost = 0
    min_w = B[0]
    for i, b in enumerate(B):
        tmp_cost = 0
        bi = A.index(b)
        cnt = 0
        while bi != i:
            cnt += 1
            st = B[bi]
            si = A.index(st)
            tmp_cost += b + st
            A[bi], A[si] = st, b
            bi = si
        if cnt:
            dec = cnt * (b - min_w)
            inc = 2 * (min_w + b)
            if dec < inc:
                cost += tmp_cost
            else:
                cost += tmp_cost - dec + inc
    return cost


n = eval(input())

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

ans = min_cost_sort(A)

print(ans)
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 912 ms):
import copy
n,k = list(map(int,input().split()))
ai = [int(i) for i in input().split()]

old_ai = ai
cnt = 0

while 1 == 1:
    old_ai = copy.deepcopy(ai)
    li = [0]*(n+1)
    for i in range(n):
        li[max(0,i-ai[i])] += 1
        li[min(n,i+1+ai[i])] -= 1
        #print(li)
    #print(li)
    tmp = 0
    for i in range(n):
        if i == 0:
            ai[i] = li[i]
            tmp += ai[i]
        else:
            ai[i] = li[i] + ai[i-1]
            tmp += ai[i]
    #print(rui)
    if ai == old_ai:
        print((*ai))
        exit()
        break
    cnt += 1
    if cnt == k:
        print((*ai))
        exit()
    old_ai = ai

Optimized program (CPU time: 246 ms):
import copy
n,k = list(map(int,input().split()))
ai = [int(i) for i in input().split()]

#old_ai = ai
cnt = 0
old_tmp = sum(ai)

while 1 == 1:
    #old_ai = copy.deepcopy(ai)
    li = [0]*(n+1)
    for i in range(n):
        li[max(0,i-ai[i])] += 1
        li[min(n,i+1+ai[i])] -= 1
        #print(li)
    #print(li)
    tmp = 0
    for i in range(n):
        if i == 0:
            ai[i] = li[i]
            tmp += ai[i]
        else:
            ai[i] = li[i] + ai[i-1]
            tmp += ai[i]
    #print(rui)
    if old_tmp == tmp:
        print((*ai))
        exit()
        break
    cnt += 1
    if cnt == k:
        print((*ai))
        exit()
    old_tmp = tmp
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 1958 ms):
import itertools
from scipy.sparse.csgraph import floyd_warshall

N, M, R = list(map(int, input().split()))
r = tuple(map(int, input().split()))

INF = 10**10

d = [[INF] * N for _ in range(N)]

for i in range(N):
    d[i][i] = 0

for _ in range(M):
    a, b, c = list(map(int, input().split()))
    a -= 1
    b -= 1
    if d[a][b] > c:
        d[a][b] = c
        d[b][a] = c


def warshall(d):
    for k in range(N):
        for i in range(N):
            for j in range(N):
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]


# d = floyd_warshall(d)
warshall(d)


ans = INF
for p in itertools.permutations(r):
    dist = 0
    for i in range(R-1):
        dist += d[p[i]-1][p[i+1]-1]

    if ans > dist:
        ans = dist

print((int(ans)))

Optimized program (CPU time: 443 ms):
import itertools

N, M, R = list(map(int, input().split()))
r = tuple(map(int, input().split()))

INF = 10**10

d = [[INF] * N for _ in range(N)]

for i in range(N):
    d[i][i] = 0

for _ in range(M):
    a, b, c = list(map(int, input().split()))
    a -= 1
    b -= 1
    if d[a][b] > c:
        d[a][b] = c
        d[b][a] = c


def warshall(d):
    for k in range(N):
        for i in range(N):
            for j in range(N):
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]


# d = floyd_warshall(d)
warshall(d)


ans = INF
for p in itertools.permutations(r):
    dist = 0
    for i in range(R-1):
        dist += d[p[i]-1][p[i+1]-1]

    if ans > dist:
        ans = dist

print((int(ans)))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 73 ms):
S = int(eval(input()))
MOD = 10 ** 9 + 7

#dp[i]最後に切った場所がi　スタートが1なのは、そこまでの切り方が1通りなので
#３以下はダメなので、3個前の結果を見るようにする
dp =  [0] * (S+1)
dp[0] = 1

for i in range(1, S+1):
    #たとえばi=6のとき、i=6で初めて切れ目を入れる時で＋１、i=3に切れ目をいれるときで＋１で合計＋２
    for j in range(0, (i-3)+1):
        dp[i] += dp[j]
        dp[i] %= MOD
print((dp[S]))        

Optimized program (CPU time: 62 ms):
S = int(eval(input()))
MOD = 10 ** 9 + 7

#dp[i]最後に切った場所がi　スタートが1なのは、そこまでの切り方が1通りなので
#３以下はダメなので、3個前の結果を見るようにする
dp =  [0] * (S+1)
dp[0] = 1

#これまでの和をxに保存しておく
x = 0
for i in range(1, S+1):
    if i-3 >= 0:
        x += dp[i-3]
        x %= MOD
    dp[i] = x
print((dp[S]))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 265 ms):
# coding: utf-8
import sys
import numpy as np

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
V = np.array(lr())
C = np.array(lr())
V -= C
V = V[V>0]
answer = V.sum()
print(answer)


Optimized program (CPU time: 18 ms):
# coding: utf-8
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N = ir()
V = lr()
C = lr()
total = 0
for i in range(N):
    result = V[i] - C[i]
    if result > 0:
        total += result

print(total)
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 450 ms):
N = int(eval(input()))
a = [int(eval(input())) for _ in range(N)]

cnt, i = 0, 0
for j in range(10 ** 6):
    cnt += 1
    if a[i] == 2:
        print(cnt)
        #break
        quit()
    else:
        i = a[i] - 1
print((-1))

Optimized program (CPU time: 202 ms):
N = int(eval(input()))
a = [int(eval(input())) for _ in range(N)]

cnt, i = 0, 0
for j in range(len(a)):
    cnt += 1
    if a[i] == 2:
        print(cnt)
        #break
        quit()
    else:
        i = a[i] - 1
print((-1))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 1852 ms):
import numpy as np

N, K = list(map(int, input().split()))
S = list((input())) + ['2']

blocks = []
cur = 1
seq = 0
for s in S:
    if int(s) == cur:
        seq += 1
    else:
        blocks.append(seq)
        cur = 1 - cur
        seq = 1
answer = 0
blocks = np.array(blocks)
for i in range(0, len(blocks), 2):
    answer = max(answer, blocks[i:i+2*K+1].sum())
print(answer)


Optimized program (CPU time: 78 ms):
# coding: utf-8
import sys
import itertools

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# 0か1の連続している人数のリスト、累積和
streak = [0, 0]
N, K = lr()
S = sr() + '2'
cur = 1
for i in range(N):
    if S[i] != S[i+1]:
        streak.append(cur)
        cur = 1
    else:
        cur += 1

streak_cum = list(itertools.accumulate(streak))
streak_cum.extend([streak_cum[-1], streak_cum[-1]])
if S[0] == '0':
    start = 0
else:
    start = 1
answer = 0

limit = len(streak_cum) - 1
for i in range(start, len(streak_cum), 2):
    result = streak_cum[min(limit, i+2*K+1)] - streak_cum[i]
    if result > answer:
        answer = result

print(answer)
# 52
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 334 ms):
import numpy as np

S=(input())
S=np.array([1 if s=='B' else 0 for s in S])

print((np.abs(np.diff(S)).sum()))


Optimized program (CPU time: 28 ms):
from itertools import groupby

S=(input())
answer = sum([1 for _ in groupby(S)]) -1

print(answer)
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 279 ms):
import sys
import numpy as np
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

n, k = list(map(int, readline().split()))
p = list(map(int, readline().split()))

tmp = [(i+1)/2 for i in p]
cs = list(np.cumsum(tmp))

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

Optimized program (CPU time: 182 ms):
import sys
# import numpy as np
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

n, k = list(map(int, readline().split()))
p = list(map(int, readline().split()))

tmp = [(i+1)/2 for i in p]
# cs = list(np.cumsum(tmp))

cs = [0]*n
cs[0] = tmp[0]
for i in range(len(tmp)-1):
    cs[i + 1] = cs[i] + tmp[i + 1]

if n == k:
    print((cs[-1]))
    exit()
ans = 0
for i in range(n - k):
    ans = max(ans, cs[i + k] - cs[i])
print(ans)
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 334 ms):
import sys
import numpy as np

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 = np.array(LI())
	A_LAST = K+A[0] - A[N-1]
	B = A[1:]-A[:N-1]
	B = np.sort(B)
	print(K-max(B[N-2],A_LAST))

if __name__ == '__main__':
	main()


Optimized program (CPU time: 121 ms):
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()