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

Original program (CPU time: 293 ms):
from collections import defaultdict

N, K, *A = list(map(int, open(0).read().split()))

S = [0] * (N + 1)
for i in range(N):
    S[i + 1] = S[i] + A[i]

d = defaultdict(int)
ans = 0
for j in range(N + 1):
    v = (S[j] - j) % K
    ans += d[v]
    d[v] += 1
    if j >= K - 1:
        d[(S[j - K + 1] - (j - K + 1)) % K] -= 1
        
print(ans)


Optimized program (CPU time: 166 ms):
from collections import defaultdict

N, K, *A = list(map(int, open(0).read().split()))

x = [0] * (N + 1)
for i in range(N):
    x[i + 1] = x[i] + A[i]
    
y = [(x[i] - i) % K for i in range(N + 1)]

ctr = defaultdict(int)
ans = 0
for j in range(N + 1):
    ans += ctr[y[j]]
    ctr[y[j]] += 1
    if j - K + 1 >= 0:
        ctr[y[j - K + 1]] -= 1
print(ans)
Task: rewrite the given python program to improve its speed of execution.

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

def bigger_devisor(n):
  s = np.sqrt(n)
  i = math.ceil(s)
  while(n % i != 0):
    i += 1
  return i

n = int(eval(input()))
if bigger_devisor(n) > 9:
  print('No')
else:
  print('Yes')

Optimized program (CPU time: 17 ms):
n = int(eval(input()))
ans = 0
for i in range(1, 10):
  if n % i == 0:
    if n / i < 10:
      ans = 1
if ans == 0:
  print('No')
else:
  print('Yes')
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 309 ms):
import numpy as np
N = int(eval(input()))
A = list(map(int, input().split()))
A = list(np.array(A) - 1)
B = list(map(int, input().split()))
C = list(map(int, input().split()))

sum_ = 0
diff = list(np.array(A[1:]) - np.array(A[:-1]))
diff.insert(0, -1)
for i in range(N):
  sum_ += B[A[i]]
  
  if diff[i] == 1:
    sum_ += C[A[i-1]]
  
print(sum_)

Optimized program (CPU time: 17 ms):
N = int(eval(input()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = list(map(int, input().split()))

ans = 0
for i in range(len(A)):
  ans += B[A[i]-1]

  if i != 0:
    if A[i-1] + 1 == A[i]:
      ans += C[A[i-1]-1]

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

Original program (CPU time: 109 ms):
N = {} #10000以上key以下の回文数の個数
cnt = 0
for i in range(10000, 100000):
    L = list(str(i))
    if L == list(reversed(L)):
        cnt += 1
    N[i] = cnt
A, B = list(map(int, input().split()))
print((N[B]-N[A-1] if A > 10000 else N[B]))

Optimized program (CPU time: 88 ms):
A, B =list(map(int, input().split()))
num_palin = [0] * (B+1)
for i in range(1,B+1):
    if str(i) == str(i)[::-1]:
        num_palin[i] = num_palin[i-1] + 1
    else:
        num_palin[i] = num_palin[i-1]
print((num_palin[B]-num_palin[A-1]))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 854 ms):
from numpy import*
a,b=median(t:=loadtxt(open(0),skiprows=1),0)
print((int((a-b)*~(~len(t)%2))+1))

Optimized program (CPU time: 417 ms):
from statistics import*
(n,),*t=[list(map(int,t.split()))for t in open(0)]
a,b=list(map(median,list(zip(*t))))
print((int((b-a)*(2-n%2))+1))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 176 ms):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

"""
奇数番目集合、偶数番目集合の中で自由にできるのが操作2．
操作1で集合間のやりとりをする
"""

import numpy as np

N = int(eval(input()))
A = np.fromstring(sys.stdin.read(),dtype=np.int64,sep='\n')

B = np.sort(A)

answer = len(np.setdiff1d(A[::2],B[::2]))
print(answer)

Optimized program (CPU time: 126 ms):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

"""
・偶数番号、奇数番号の中では入れ替え放題
・偶、奇の間：並べてからスワップ。操作2を1回で、正しいものを2つ増やせる
"""

N,*A = list(map(int,read().split()))

x_to_i = {x:i for i,x in enumerate(sorted(A))}
rank = [x_to_i[x] for x in A]

answer = sum((x^i) & 1 for i,x in enumerate(rank)) // 2
print(answer)
Task: rewrite the given python program to improve its speed of execution.

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

n = int(eval(input()))
dp = np.zeros((n+10, 3))

def cmax(a,b):
    if a>b:
        return a
    else: 
        return b
        
for i in range(1, n+1):
    a, b, c = list(map(int, input().split()))
    # a
    dp[i][0] = cmax(dp[i-1][1]+a, dp[i-1][2]+a)
    # b
    dp[i][1] = cmax(dp[i-1][0]+b, dp[i-1][2]+b)
    # c
    dp[i][2] = cmax(dp[i-1][0]+c, dp[i-1][1]+c)

print((int(max(dp[i,:]))))

Optimized program (CPU time: 509 ms):
# coding: utf-8
# Your code here!


N = int(eval(input()))

dp = [[0]*3 for _ in range(N+1)]

for i in range(1, N+1):
    a, b, c = list(map(int, input().split()))
    dp[i][0] = max(dp[i-1][1], dp[i-1][2]) + a
    dp[i][1] = max(dp[i-1][0], dp[i-1][2]) + b
    dp[i][2] = max(dp[i-1][0], dp[i-1][1]) + c
    
print((max(dp[N])))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 186 ms):
import numpy as np
N,M=list(map(int,input().split()))
A=np.zeros((N+1,M+1))
A[0]=np.ones(M+1)
for i in range(1,N+1):
    B=list(map(int,input().split()))
    for m in range(1,B[0]+1):
        A[i][B[m]]=A[i-1][B[m]]
a=sum(A[N])
print((int(a)))

Optimized program (CPU time: 18 ms):
N,M=list(map(int,input().split()))
A = [[1 for _ in range(M)]]+[[0 for _ in range(M)] for _ in range(N)]
for i in range(1,N+1):
    B=list(map(int,input().split()))
    Ai=B[1:]
    for m in Ai:
        A[i][m-1]=A[i-1][m-1]
a=sum(A[N])
print((int(a)))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 472 ms):
# temp
n,w = list(map(int,input().split()))
wv = [tuple(map(int,input().split())) for i in range(n)]

dp = [0] + [float("inf")]*(10**5)
for i in range(n):
    for j in range(10**5,wv[i][1]-1,-1):
        dp[j] = min(dp[j],dp[j-wv[i][1]]+wv[i][0])

res = 0
for v,e in enumerate(dp):
    if e <= w:
        res = v
print(res)

Optimized program (CPU time: 351 ms):
# dpE - Knapsack 2
import sys
input = sys.stdin.readline

def main():
    n, W = tuple(map(int, input().rstrip().split()))
    A = tuple(tuple(map(int, input().rstrip().split())) for _ in range(n))
    _, v = list(zip(*A))
    lim = sum(v)
    dp = [0] + [float("inf")] * lim
    for i in range(n):
        for j in range(lim, A[i][1] - 1, -1):
            dp[j] = min(dp[j], dp[j - A[i][1]] + A[i][0])
    ans = max(v for v, w in enumerate(dp) if w <= W)
    print(ans)


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

Original program (CPU time: 604 ms):
# 2019-11-12 22:21:08(JST)
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
import itertools
# from functools import reduce
# import operator as op
# from scipy.misc import comb # float
# import numpy as np 

def main():
    s = sys.stdin.readline().rstrip()
    
    all_words = []
    for i in range(1, len(s) + 1):
        for letters in itertools.product('ATCG', repeat=i):
            word = ''.join(letters)
            all_words.append(word)
    
    for i in range(len(all_words)-1, 0-1, -1):
        if all_words[i] in s:
            print((len(all_words[i])))
            sys.exit()
    print((0))




if __name__ == "__main__":
    main()


Optimized program (CPU time: 18 ms):
# 2019-11-12 22:21:08(JST)
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# from scipy.misc import comb # float
# import numpy as np 

def main():
    s = sys.stdin.readline().rstrip()
    
    permitted = 'ACGT'
    continuous_count = []
    count = 0

    for i in range(len(s)):
        char = s[i]
        if char in permitted:
            count += 1
        else:
            continuous_count.append(count)
            count = 0
        if i == len(s) - 1:
            continuous_count.append(count)
    
    if not continuous_count:
        print((len(s)))
    else:
        print((max(continuous_count)))



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

Original program (CPU time: 224 ms):
def resolve():
    '''
    code here
    '''
    import collections
    import itertools
    import numpy as np
    N = int(eval(input()))
    Ss = [input()[0] for _ in range(N)]

    march_letter = [item for item in Ss if item in ['M', 'A', 'R', 'C', 'H']]
    march_cnt = collections.Counter(march_letter)

    if len(march_cnt) < 3:
        res = 0
    else:
        res_list = itertools.combinations(list(march_cnt.values()),3)

        res = 0
        for element in res_list:
            res += np.prod(np.array(element))
    print(res)

if __name__ == "__main__":
    resolve()


Optimized program (CPU time: 139 ms):
def resolve():
    '''
    code here
    '''
    import collections
    import itertools
    N = int(eval(input()))
    Ss = [input()[0] for _ in range(N)]

    march_letter = [item for item in Ss if item in ['M', 'A', 'R', 'C', 'H']]
    march_cnt = collections.Counter(march_letter)

    if len(march_cnt) < 3:
        res = 0
    else:
        res_list = itertools.combinations(list(march_cnt.values()),3)

        res = 0
        for element in res_list:
            res += element[0]*element[1]*element[2]
    print(res)

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

Original program (CPU time: 306 ms):
import numpy as np
from itertools import product

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

a = np.array(a)

li = [-1,0,1]
cnt = 0
for v in product(li,repeat = n):
    v = np.array(v)
    L =a+v
    cum = L.cumprod()
    if cum[-1]%2 ==0 :
        cnt +=1
print(cnt)
        

Optimized program (CPU time: 168 ms):
n = int(eval(input()))
a = list(map(int,input().split()))

from itertools import product

li = [-1,0,1]
cnt = 0
for v in product(li,repeat = n):
    L = []
    for i in range(n):
        L.append(v[i]+a[i])
    if any(x%2==0 for x in L):
        cnt +=1

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

Original program (CPU time: 25 ms):
from string import ascii_lowercase as lower
print((lower[lower.find((input()))+1]))

Optimized program (CPU time: 17 ms):
print((chr(ord((input()))+1)))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 36 ms):
X, Y, Z = list(map(int, input().split()))
for n in range(10 ** 5, 0, -1):
    if X >= n * (Y + Z) + Z:
        break
print(n)

Optimized program (CPU time: 18 ms):
X, Y, Z = list(map(int, input().split()))
print(((X - Z) // (Y + Z)))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 28 ms):
array = list(map(int, input().split()))
if array[0] % array[1] > 0:
    print(((array[0] // array[1] + 1) * array[2]))
else:
    print(((array[0] // array[1]) * array[2]))

Optimized program (CPU time: 25 ms):
n, x, t = list(map(int, input().split()))

print((0--n//x*t))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 27 ms):
N = int(eval(input()))
L = [ 0 ] * 1000000

L[0] = 2
L[1] = 1

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

print((L[N]))


Optimized program (CPU time: 17 ms):
N = int(eval(input()))
L = [ 0 ] * (N+1)

L[0] = 2
L[1] = 1

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

print((L[N]))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 415 ms):
from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall

INF = float('inf')

def sol():
    N, M = list(map(int, input().split()))

    edges = []

    for _ in range(M):
        fr, to, cost = list(map(int, input().split()))
        fr -= 1
        to -= 1
        edges.append((fr, to, cost))

    graph = [[INF] * N for _ in range(N)]
    for fr, to, cost in edges:
        graph[fr][to] = cost

    graph = csgraph_from_dense(graph, null_value=INF)

    dist = floyd_warshall(graph, directed=False)
    ans = (graph > dist).sum()
    print(ans)

sol()

Optimized program (CPU time: 231 ms):
N, M = list(map(int, input().split()))
INF = 10**18

minDist = [[INF] * N for _ in range(N)]
for i in range(N):
    minDist[i][i] = 0

edges = []
for _ in range(M):
    fr, to, d = list(map(int, input().split()))
    fr -= 1
    to -= 1
    edges.append((fr, to, d))
    minDist[fr][to] = d
    minDist[to][fr] = d

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

ans = 0
for fr, to, d in edges:
    if minDist[fr][to] < d:
        ans += 1
print(ans)
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 149 ms):
import numpy as np
N,x = list(map(int,input().split()))
A = np.array(input().split(), dtype = np.int64)
A.sort()
np.cumsum(A, out = A)
answer = (A <= x).sum()

if answer == N and A[-1] != x:
  answer -= 1
print(answer)


Optimized program (CPU time: 18 ms):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from bisect import bisect_right
import itertools

N,X,*A = list(map(int,read().split()))

A.sort()
Acum = list(itertools.accumulate(A))

answer = bisect_right(Acum,X)
if answer == N:
    if Acum[-1] < X:
        answer -= 1
print(answer)
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 161 ms):
import numpy as np
 
def main():
    stdin = np.fromstring(open(0).read(), dtype=np.int64, sep=' ')
    A = stdin[1:]
    A = np.mod(A, 2)
    print("first") if np.count_nonzero(A) else print("second")
if __name__ == "__main__":
    main()


Optimized program (CPU time: 94 ms):
import sys
def input(): return sys.stdin.readline().strip()
def main():
    N = int(input())
    A = (int(input()) for _ in range(N))
    print("second") if all(( a%2==0 for a in A)) else print("first")
if __name__ == "__main__":
    main()
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 1298 ms):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from operator import xor
from functools import reduce

N,K,*A = list(map(int,read().split()))

a = reduce(xor,(1<<a for a in A))

dp = 0 # bitset
for n in range(K):
    if not(dp&(1<<n)):
        dp |= (a<<n)

answer = 'First' if dp&(1<<K) else 'Second'
print(answer)

Optimized program (CPU time: 123 ms):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N,K,*A = list(map(int,read().split()))

dp = [0]*(K+1) # bitset
for n in range(K):
    if not dp[n]:
        for a in A:
            if n+a>K:
                break
            dp[n+a]=1

answer = 'First' if dp[-1] else 'Second'
print(answer)
Task: rewrite the given python program to improve its speed of execution.

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

N = int(eval(input()))
A = [0] + list(map(int, input().split()))

A = np.array(A, dtype = np.int64)
A = np.cumsum(A)

dp = np.zeros((N, N), dtype = np.int64)

for j in range(1, N):
    for i in range(N - j):
        # print (dp[i, i:i + j], dp[i + 1:i + j + 1, i + j])
        tmp = min(dp[i, i:i + j] + dp[i + 1:i + j + 1, i + j])
        dp[i][i + j] = tmp + A[i + j + 1] - A[i]

print((dp[0][N - 1]))

Optimized program (CPU time: 405 ms):
N = int(eval(input()))
A = [0] + list(map(int, input().split()))

INF = 10 ** 18

dp = [[0] * (N) for _ in range(N)]

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

for j in range(1, N):
    for i in range(N - j):
        tmp = INF
        for k in range(i, i + j):
            # print (i, i + j, k + 1)
            tmp = min(tmp, dp[i][k] + dp[k + 1][i + j])
        dp[i][i + j] = tmp + A[i + j + 1] - A[i]

print((dp[0][N - 1]))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 585 ms):
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n = inp()
A = sorted(inpl())
B = sorted(inpl())
C = sorted(inpl())
cnt = [0] * n
res = 0
for i,b in enumerate(B):
    c = bisect.bisect_left(C,b+1)
    cnt[i] = n-c

acc = [0]
for x in cnt:
    acc += [acc[-1] + x]
su = sum(cnt) 
for i,a in enumerate(A):
    c = bisect.bisect_left(B,a+1)
    res += su - acc[c]
print(res)

Optimized program (CPU time: 431 ms):
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n = inp()
a = inpl()
b = inpl()
c = inpl()
a.sort()
b.sort()
c.sort()
lb = [0] * n
res = 0
for i in range(n):
    tmp = bisect.bisect_right(b,a[i])
    if tmp == n: continue
    lb[tmp] += 1
llb = list(itertools.accumulate(lb))
# print(lb,llb)
rr = [0] * n
for i in range(n):
    tmp = bisect.bisect_right(c,b[i])
    if tmp == n: continue
    rr[tmp] += llb[i]
print((sum(list(itertools.accumulate(rr)))))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 620 ms):
import numpy as np
s = (input())
y = 2019
dp = np.zeros(y, dtype="int64")
tmp = np.zeros(y, dtype="int64")
k = 1
r = 0
for c in s[::-1]:
    i = int(c)*k%y
    tmp[i:] = dp[:y-i]
    tmp[:i] = dp[y-i:]
    tmp[i] += 1
    dp, tmp = tmp, dp
    r += dp[0]
    k *= 10
    k %= y
print(r)

Optimized program (CPU time: 135 ms):
y=2019
a=[0]*y
k=1
r=p=0
for c in input()[::-1]:
    a[p]+=1
    p-=int(c)*k
    p%=y
    r+=a[p]
    k*=10
    k%=y
print(r)
Task: rewrite the given python program to improve its speed of execution.

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

N, M = [int(_) for _ in input().split()]

if M == 0:
    if N == 1:
        print("0")
    else:
        ans = [0] * N
        ans[0] = 1
        print(("".join(map(str, ans))))
    sys.exit()

S, C = np.array([[int(_) for _ in input().split()] for i in range(M)]).T

ans = [-1] * N

for i in range(M):
    j = int(S[i]) - 1
    if ans[j] == -1 or ans[j] == C[i]:
        ans[j] = C[i]
    else:
        print("-1")
        sys.exit()

if N >= 2 and ans[0] == 0:
    print("-1")
    sys.exit()

if N >= 2 and ans[0] == -1:
    ans[0] = 1

for i in range(1, N):
    if ans[i] == -1:
        ans[i] = 0

s = "".join(map(str, ans))
print(s)


Optimized program (CPU time: 30 ms):
import sys

N, M = [int(_) for _ in input().split()]
SC = [[int(_) for _ in input().split()] for i in range(M)]

if N == 1:
    start = 0
    end = 10
else:
    start = 10 ** (N - 1)
    end = 10 ** N

for i in range(start, end):
    ans = list(map(int, str(i)))
    valid = True
    for s, c in SC:
        if ans[s-1] != c:
            valid = False
            break
    if valid:
        print(i)
        sys.exit()

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

Original program (CPU time: 737 ms):
from scipy.sparse.csgraph import dijkstra
N, M = list(map(int, input().split()))
edge = [list(map(int, input().split())) for _ in range(M)]

# 隣接行列
graph = [[0] * (N + 1) for _ in range(N + 1)]

for i, j in edge:
  graph[i][j] = 1
  
ans = 0
INF = 10 ** 9
for a, b in edge:
  # 辺を取り除く-> INF
  graph[a][b] = INF
  dist = dijkstra(graph, indices=a, directed=False) # directed=False -> 無効グラフ用
  if dist[b] >= INF:
    ans += 1
  # 元に戻す -> 1
  graph[a][b] = 1

print(ans)

Optimized program (CPU time: 23 ms):
# C - Bridge
# https://atcoder.jp/contests/abc075/tasks/abc075_c

from collections import deque

def dfs(n, start, graph):
  visited = [False] * n
  stack = deque()
  stack.append(start)
  visited[start] = True
  while stack:
    q = stack.popleft()
    nxts = graph[q]
    for nxt in nxts:
      if not visited[nxt]:
        visited[nxt] = True
        stack.append(nxt)
  return visited

n, m = list(map(int, input().split()))
edge = [list(map(int, input().split())) for _ in range(m)]

ans = 0
for i in range(m):
  graph = [[] for _ in range(n)]
  for itr, (a, b) in enumerate(edge):
    if itr != i:
      graph[a - 1].append(b - 1)
      graph[b - 1].append(a - 1)

  if not all(dfs(n, 0, graph)):
    ans += 1

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

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


def solve(*args: str) -> str:
    n = int(args[0])
    LR = [tuple(map(int, a.split())) for a in args[1:]]
    L, R = list(zip(*LR))

    ret = 0

    p, q = np.argmax(L), np.argmin(R)
    lp, rq = L[p], R[q]

    ret = max(0, 1+rq-lp) + max(0, max(1+r-l for l, r in LR))

    AB = [[max(0, 1+r-lp), max(0, 1+rq-l)] for l, r in LR]
    AB.sort(key=lambda x: (x[0], -x[1]))
    A, B = list(map(list, list(zip(*AB))))

    # for i in range(1, n):
    #     ret = max(ret, min(A[i:]) + min(B[:i]))
    b_min = 1+10**9
    for i in range(n-1):
        b_min = min(b_min, B[i])
        ret = max(ret, b_min + A[i+1])

    return str(ret)


if __name__ == "__main__":
    print((solve(*(open(0).read().splitlines()))))


Optimized program (CPU time: 607 ms):
# coding: utf-8


def solve(*args: str) -> str:
    n = int(args[0])
    LR = [tuple(map(int, a.split())) for a in args[1:]]
    L, R = list(zip(*LR))

    ret = 0

    # lp, rq = max(L), min(R)
    lp, rq = 0, 1+10**9
    for l, r in LR:
        lp, rq = max(lp, l), min(rq, r)

    ret = max(0, 1+rq-lp) + max(0, max(1+r-l for l, r in LR))

    AB = [[max(0, 1+r-lp), max(0, 1+rq-l)] for l, r in LR]
    AB.sort(key=lambda x: (x[0], -x[1]))
    A, B = list(map(list, list(zip(*AB))))

    # for i in range(1, n):
    #     ret = max(ret, min(A[i:]) + min(B[:i]))
    b_min = 1+10**9
    for i in range(n-1):
        b_min = min(b_min, B[i])
        ret = max(ret, b_min + A[i+1])

    return str(ret)


if __name__ == "__main__":
    print((solve(*(open(0).read().splitlines()))))
Task: rewrite the given python program to improve its speed of execution.

Original program (CPU time: 150 ms):
N=int(eval(input()))
d=list(map(int, input().split()))

import numpy as np
d = np.array(d)

print(( ( (np.sum(d))**2 - np.sum(d**2) ) // 2 ))


Optimized program (CPU time: 17 ms):
N=int(eval(input()))
d=list(map(int, input().split()))

cumsum = 0
for n in range(N):
    cumsum += d[n]
sub_cumsum = 0
ans = 0
for n in range(N):
    sub_cumsum += d[n]
    ans += d[n] * (cumsum-sub_cumsum)
print(ans)