Problem:


Score : 800 points

Problem Statement

Takahashi Lake has a perimeter of L. On the circumference of the lake, there is a residence of the lake's owner, Takahashi.
Each point on the circumference of the lake has a coordinate between 0 and L (including 0 but not L), which is the distance from the Takahashi's residence, measured counter-clockwise.

There are N trees around the lake; the coordinate of the i-th tree is X_i. There is no tree at coordinate 0, the location of Takahashi's residence.

Starting at his residence, Takahashi will repeat the following action:

If all trees are burnt, terminate the process.

Specify a direction: clockwise or counter-clockwise.

Walk around the lake in the specified direction, until the coordinate of a tree that is not yet burnt is reached for the first time.

When the coordinate with the tree is reached, burn that tree, stay at the position and go back to the first step.

Find the longest possible total distance Takahashi walks during the process.

Partial Score

A partial score can be obtained in this problem:

300 points will be awarded for passing the input satisfying N \leq 2000.

Constraints

2 \leq L \leq 10^9

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

1 \leq X_1 < ... < X_N \leq L-1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

L N
X_1
:
X_N

Output

Print the longest possible total distance Takahashi walks during the process.

Sample Input 1

10 3
2
7
9

Sample Output 1

15

Takahashi walks the distance of 15 if the process goes as follows:

Walk a distance of 2 counter-clockwise, burn the tree at the coordinate 2 and stay there.

Walk a distance of 5 counter-clockwise, burn the tree at the coordinate 7 and stay there.

Walk a distance of 8 clockwise, burn the tree at the coordinate 9 and stay there.

Sample Input 2

10 6
1
2
3
6
7
9

Sample Output 2

27

Sample Input 3

314159265 7
21662711
77271666
89022761
156626166
160332356
166902656
298992265

Sample Output 3

1204124749



Sample input:
10 3
2
7
9


Sample output:
15

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 30 09:04:16 2018

@author: Yamazaki Kenichi
"""
L,N = map(int, input().split(' '))
X = [int(input()) for i in range(N) ]

Xr = [0] + X

Yr = ["d"]
for i in range(0,N):
    Yr.append( Xr[i+1] - Xr[i])

Yl = ["d"]+[L-X[N-1]]
Yl += Yr[::-1]

S = []

answer = 0
for itr in range(1,N+1):
    sum = 0
    counter = 1
    while counter <= itr:
        sum += Yr[counter]
        counter += 1
        
    turn = counter-1
    counter2 = 1
    sum2 = sum
    while counter <= N:
        if counter2 % 2 ==1:
            sum2 += Yl[counter2//2+1]
            sum += sum2 
        else:
            sum2 += Yr[turn + counter2//2]
            sum += sum2
        counter += 1
        counter2 += 1
#    print(sum)
#    S.append(sum)
    answer = max(answer,sum)

for itr in range(1,N+1):
    sum = 0
    counter = 1
    while counter <= itr:
        sum += Yl[counter]
        counter += 1
    turn = counter-1
    counter2 = 1
    sum2 = sum
    while counter <= N:
        if counter2 % 2 ==1:
            sum2 += Yr[counter2//2+1]
            sum += sum2 
        else:
            sum2 += Yl[turn + counter2//2]
            sum += sum2
        counter += 1
        counter2 += 1
    answer = max(answer,sum)
print(answer)

Submission status: Time Limit Exceeded

Solution code:
L,N=map(int,input().split())
tree=[]
trcp=[]
for i in range(N):
  trcp.append(int(input()))
ans=0
for i in range(N):
  tree=[x for x in trcp]
  tree2=[x for x in trcp]
  t=0
  t2=0
  road=0
  roadr=0
  for ii in range(N):
    if ii>i and (ii-i)%2==1:
      road+=L-tree[-1]+t
      t=tree[-1]-L
      del tree[-1]
      roadr+=tree2[0]-t2
      t2=tree2[0]
      del tree2[0]
    else:
      road+=tree[0]-t
      t=tree[0]
      del tree[0]
      roadr+=L-tree2[-1]+t2
      t2=tree2[-1]-L
      del tree2[-1]
    
  if road>ans:
    ans=road
  if roadr>ans:
    ans=roadr
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
L, N = map(int, input().split())
X = [0] + [int(input()) for _ in range(N)]
Y = [0] + [L - x for x in X[1:]][::-1]

dp = [[[0] * 2 for _ in range(N + 1)] for _ in range(N + 1)]
for i in range(N):
    for j in range(N):
        dp[i + 1][j][0] = max(
                dp[i][j][0] + Y[i + 1] - Y[i],
                dp[i][j][1] + X[j] + Y[i + 1])
        dp[i][j + 1][1] = max(
                dp[i][j][0] + X[j + 1] + Y[i],
                dp[i][j][1] + X[j + 1] - X[j])

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

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import time
L,N=map(int,input().split())
tree=[]
trcp=[]
list0=[]
for i in range(N):
  trcp.append(int(input()))
  if i%2==0:
    list0.append(0)
  else:
    list0.append(-1)
pat=[]
patrev=[0]*N
for i in range(N):
  patx=[0]*N
  patrev=[0]*N
  for ii in range(N):
    if ii>i:
      patx[ii]=list0[ii-i]
    patrev[ii]=-1-patx[ii]
  pat.append(patx)
  pat.append(patrev)
  
t2=time.time()
ans=0
for l in pat:
  tree=[x for x in trcp]
  t=0
  road=0
  for i in range(N):
    if l[i]==0:
      road+=tree[0]-t
      t=tree[0]
      del tree[0]
    else:
      road+=L-tree[-1]+t
      t=tree[-1]-L
      del tree[-1]
  if road>ans:
    ans=road
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
fin = sys.stdin.readline
sys.setrecursionlimit(5000000)
# from queue import deque
from functools import lru_cache

L, N = [int(elem) for elem in fin().split()]
X_list = [0]
X_list.extend([int(fin()) for _ in range(N)])
X_list.append(L)
N += 2

# this does not work in PyPy because of the slowness
# memo = [[[None] * 2  for _ in range(N + 1)] for _ in range(N + 1)]

# @lru_cache(None)
# def rec(i, j, front):
#     if memo[i][j][front] is not None:
#         return memo[i][j][front]
#     else:
#         if i == j:
#             max_dist = 0
#         else:
#             head = X_list[i]
#             tail = X_list[j - 1]
#             if front == 1:
#                 k = X_list[i - 1]
#                 max_dist = max(rec(i + 1, j, 1) + head - k, rec(i, j - 1, 0) + L + k - tail)
#             else:
#                 k = X_list[j]
#                 max_dist =  max(rec(i + 1, j, 1) + L + head - k, rec(i, j - 1, 0) + k - tail)
#         memo[i][j][front] = max_dist
#         return max_dist
# print(max(rec(1, N, 1) + X_list[0], rec(0, N - 1, 0) + L - X_list[-1]))


# dp[i][j][k] = the longest possible total distance when the trees of X_list[i:j] are available
# and **coming from k (k == 1 -> forward, otherwise backward)**
dp = [[[0] * 2 for _ in range(N + 1)] for _ in range(N + 1)]
# dp[0][1][1] = X_list[0]
# dp[0][1][0] = X_list[1] - X_list[0]
# for i in range(1, N - 1):
#     lo, mid, hi = X_list[i - 1:i + 2]
#     dp[i][i + 1][1] = max(mid - lo, L + lo - mid)
#     dp[i][i + 1][0] = max(hi - mid, L + mid - hi)

for w in range(1, N + 1):
    for start in range(1, N - w):
        end = start + w
        dp[start][end][1] = max(dp[start + 1][end][1] + X_list[start] - X_list[start - 1],
                                dp[start][end - 1][0] + L + X_list[start - 1] - X_list[end - 1])
        dp[start][end][0] = max(dp[start + 1][end][1] + L + X_list[start] - X_list[end],
                                dp[start][end - 1][0] + X_list[end] - X_list[end - 1])

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

Submission status: Time Limit Exceeded

Solution code:
import time
L,N=map(int,input().split())
tree=[]
trcp=[]
for i in range(N):
  trcp.append(int(input()))
list0=[]
for i in range(N):
  if i%2==0:
    list0.append(0)
  else:
    list0.append(-1)
pat=[]
patrev=[0]*N
for i in range(N):
  patx=[0]*N
  patrev=[0]*N
  for ii in range(N):
    if ii>i:
      patx[ii]=list0[ii-i]
    patrev[ii]=-1-patx[ii]
  pat.append(patx)
  pat.append(patrev)
  
ans=0
for l in pat:
  tree=[x for x in trcp]
  t=0
  road=0
  for i in range(N):
    if l[i]==0:
      road+=tree[0]
      t=tree[0]
      del tree[0]
    else:
      road+=L-tree[-1]
      t=tree[-1]-L
      del tree[-1]
    tree=[x-t for x in tree] 
  if road>ans:
    ans=road
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
fin = sys.stdin.readline
sys.setrecursionlimit(5000000)
from queue import deque
from functools import lru_cache

L, N = [int(elem) for elem in fin().split()]
X_list = [int(fin()) for _ in range(N)]
# X_list.append(L)


# this does not work in PyPy because of the slowness
memo = [[[None] * 2  for _ in range(N + 1)] for _ in range(N + 1)]

@lru_cache(None)
def rec(i, j, front):
    if memo[i][j][front] is not None:
        return memo[i][j][front]
    else:
        if i == j:
            max_dist = 0
        else:
            head = X_list[i]
            tail = X_list[j - 1]
            if front == 1:
                k = X_list[i - 1]
                max_dist = max(rec(i + 1, j, 1) + head - k, rec(i, j - 1, 0) + L + k - tail)
            else:
                k = X_list[j]
                max_dist =  max(rec(i + 1, j, 1) + L + head - k, rec(i, j - 1, 0) + k - tail)
        memo[i][j][front] = max_dist
        return max_dist
print(max(rec(1, N, 1) + X_list[0], rec(0, N - 1, 0) + L - X_list[-1]))

Submission status: Time Limit Exceeded

Solution code:
L,N=map(int,input().split())
tree=[]
for i in range(N):
  tree.append(int(input()))
trcp=tree
seq=(0,-1)
listz=[0]*N
list0=[]
list1=[-1]*N
for i in range(N):
  if i%2==0:
    list0.append(0)
  else:
    list0.append(-1)
pat=[]
patrev=[0]*N
for i in range(N):
  patx=[0]*N
  patrev=[0]*N
  for ii in range(N):
    if ii>i:
      patx[ii]=list0[ii-i]
    patrev[ii]=-1-patx[ii]
  pat.append(patx)
  pat.append(patrev)
  
ans=[]
tree=[]
for l in pat:
  for j in range(N):
    tree.append(trcp[j])
  t=0
  road=0
  for i in range(N):
    if l[i]==0:
      road+=tree[0]
      t=tree[0]
      del tree[0]
    else:
      road+=L-tree[-1]
      t=tree[-1]-L
      del tree[-1]
    for k in range(len(tree)):
        tree[k]=tree[k]-t 
  ans.append(road)
print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
(L, N) = map(int, input().split())
X = [0 for i in range(N)]
for i in range(N):
    X[i] = int(input())


ans = 0
if N == 1:
    ans = max(X[0], L-X[0])
else:
    X += X
    #print('X: ', X)
    dmax = 0
    for i in range(1, N):
        seg = X[i:i+N]
        #print('seg: ', seg)
        for s in (0, N-1):
            os = (N-1)-s
            cl = N-1    # counterclockwise most
            cr = 0      # clockwise most
            d = 0
            lflg = False
            if s == cl:
                lflg = True
            while True:
                #print('tmpd: ', d)
                # l to l
                if lflg and seg[s] >= seg[os]:
                    d += seg[s]
                    break
                # r to r
                elif not(lflg) and seg[s] <= seg[os]:
                    d += L-seg[s]
                    break
                
                # l to r
                if lflg:
                    d += seg[s]+(L-seg[os])
                    # update segment
                    cl = s-1 if s-1>=0 else N-1 # move to r by 1
                    cr = os
                    # next
                    s = cr
                    os = cl
                # r to l
                else:
                    d += seg[os]+(L-seg[s])
                    # update segment
                    cl = os
                    cr = s+1 if s+1 < N else 0  # move to l by 1
                    # next
                    s = cl
                    os = cr
                lflg = not(lflg)
            #print('d: ', d)
            if d > dmax:
                dmax = d
    ans = dmax

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

stdin = sys.stdin

sys.setrecursionlimit(10 ** 5)


def li(): return map(int, stdin.readline().split())


def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())


def lf(): return map(float, stdin.readline().split())


def ls(): return stdin.readline().split()


def ns(): return stdin.readline().rstrip()


def lc(): return list(ns())


def ni(): return int(stdin.readline())


def nf(): return float(stdin.readline())


l, n = li()
x = [ni() for _ in range(n)]

#dp = [[[0, 0] for _ in range(n + 1)] for _ in range(n + 1)]
dp0 = [[0]*(n+1) for _ in range(n + 1)]
dp1 = [[0]*(n+1) for _ in range(n + 1)]
left = [0] + x
right = [l] + x[::-1]

for total in range(1, n + 1):
    for ccw in range(total + 1):
        cw = total - ccw
        if ccw == 0:
            dp1[ccw][cw] = dp1[ccw][cw - 1] + (right[cw - 1] - right[cw])

        elif cw == 0:
            dp0[ccw][cw] = dp0[ccw - 1][cw] + (left[ccw] - left[ccw - 1])

        else:
            dp0[ccw][cw] = max(dp1[ccw - 1][cw] + (left[ccw] + l - right[cw]),
                                 dp0[ccw - 1][cw] + (left[ccw] - left[ccw - 1]))

            dp1[ccw][cw] = max(dp1[ccw][cw - 1] + (right[cw - 1] - right[cw]),
                                 dp0[ccw][cw - 1] + (left[ccw] + l - right[cw]))
ans = 0
for ccw in range(n + 1):
    cw = n - ccw
    ans = max(ans, dp0[ccw][cw], dp1[ccw][cw])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


l,n = li()
x = [ni() for _ in range(n)]

dp = [[[0,0] for _ in range(n+1)] for _ in range(n+1)]
left = [0] + x
right = [l] + x[::-1]

for total in range(1,n+1):
    for ccw in range(total+1):
        cw = total - ccw
        if ccw == 0:
            dp[ccw][cw][1] = dp[ccw][cw-1][1] + (right[cw-1] - right[cw])
            
        elif cw == 0:
            dp[ccw][cw][0] = dp[ccw-1][cw][0] + (left[ccw] - left[ccw-1])
        
        else:
            dp[ccw][cw][0] = max(dp[ccw-1][cw][1] + (left[ccw] + l - right[cw]),
                                 dp[ccw-1][cw][0] + (left[ccw] - left[ccw-1]))

            dp[ccw][cw][1] = max(dp[ccw][cw-1][1] + (right[cw-1] - right[cw]),
                                 dp[ccw][cw-1][0] + (left[ccw] + l - right[cw]))
ans = 0
for ccw in range(n+1):
    cw = n - ccw
    ans = max(ans, dp[ccw][cw][0], dp[ccw][cw][1])
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


l,n = li()
x = [ni() for _ in range(n)]

dp = [[[0,0] for _ in range(n+1)] for _ in range(n+1)]
left = [0] + x
right = [l] + x[::-1]

for total in range(1,n+1):
    for ccw in range(total+1):
        cw = total - ccw
        if ccw == 0:
            dp[ccw][cw][1] = dp[ccw][cw-1][1] + (right[cw-1] + l - right[cw]) % l
            
        elif cw == 0:
            dp[ccw][cw][0] = dp[ccw-1][cw][0] + (left[ccw] + l - left[ccw-1]) % l
        
        else:
            dp[ccw][cw][0] = max(dp[ccw-1][cw][1] + (left[ccw] + l - right[cw]) % l,
                                 dp[ccw-1][cw][0] + (left[ccw] + l - left[ccw-1]) % l)

            dp[ccw][cw][1] = max(dp[ccw][cw-1][1] + (right[cw-1] + l - right[cw]) % l,
                                 dp[ccw][cw-1][0] + (left[ccw] + l - right[cw]) % l)
ans = 0
for ccw in range(n+1):
    cw = n - ccw
    ans = max(ans, dp[ccw][cw][0], dp[ccw][cw][1])
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


l,n = li()
x = [ni() for _ in range(n)]

dp = [[[0, 0] for _ in range(n+1)] for _ in range(n+1)]
left = [0] + x
right = [l] + x[::-1]
dp[1][0][1] = left[1] - left[0]
dp[0][1][0] = right[0] - right[1]

for cw in range(n):
    for ccw in range(n):
        if cw+ccw >= n:
            break
        
        if dp[ccw][cw][0]:
            dp[ccw+1][cw][1] = max(dp[ccw+1][cw][1], dp[ccw][cw][0] + (l + left[ccw+1] - right[cw]))
            dp[ccw][cw+1][0] = max(dp[ccw][cw+1][0], dp[ccw][cw][0] + (right[cw] - right[cw+1]))
            
        if dp[ccw][cw][1]:
            dp[ccw+1][cw][1] = max(dp[ccw+1][cw][1], dp[ccw][cw][1] + (left[ccw+1] - left[ccw]))
            dp[ccw][cw+1][0] = max(dp[ccw][cw+1][0], dp[ccw][cw][1] + (l + left[ccw] - right[cw+1]))

ans = 0
for ccw in range(n+1):
    cw = n - ccw
    ans = max(ans, dp[ccw][cw][0], dp[ccw][cw][1])
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


l,n = li()
x = [ni() for _ in range(n)]

dp = [[[0 for _ in range(2)] for _ in range(n+1)] for _ in range(n+1)]
left = [0] + x
right = [l] + x[::-1]
dp[1][0][1] = (left[1] - left[0]) % l
dp[0][1][0] = (right[0] - right[1]) % l

for cw in range(n):
    for ccw in range(n):
        if cw+ccw >= n:
            break
        
        if dp[ccw][cw][0]:
            dp[ccw+1][cw][1] = max(dp[ccw+1][cw][1], dp[ccw][cw][0] + (left[ccw+1] - right[cw]) % l)
            dp[ccw][cw+1][0] = max(dp[ccw][cw+1][0], dp[ccw][cw][0] + (right[cw] - right[cw+1]) % l)
            
        if dp[ccw][cw][1]:
            dp[ccw+1][cw][1] = max(dp[ccw+1][cw][1], dp[ccw][cw][1] + (left[ccw+1] - left[ccw]) % l)
            dp[ccw][cw+1][0] = max(dp[ccw][cw+1][0], dp[ccw][cw][1] + (left[ccw] - right[cw+1]) % l)

ans = 0
for ccw in range(n+1):
    cw = n - ccw
    ans = max(ans, dp[ccw][cw][0], dp[ccw][cw][1])
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


l,n = li()
x = [ni() for _ in range(n)]

dp = [[[0 for _ in range(2)] for _ in range(n+1)] for _ in range(n+1)]
left = [0] + x
right = [l] + x[::-1]
dp[1][0][1] = (left[1] + l - left[0]) % l
dp[0][1][0] = (right[0] + l - right[1]) % l

for cw in range(n):
    for ccw in range(n):
        if cw+ccw >= n:
            break
        
        if dp[ccw][cw][0]:
            dp[ccw+1][cw][1] = max(dp[ccw+1][cw][1], dp[ccw][cw][0] + (left[ccw+1] + l - right[cw]) % l)
            dp[ccw][cw+1][0] = max(dp[ccw][cw+1][0], dp[ccw][cw][0] + (right[cw] + l - right[cw+1]) % l)
            
        if dp[ccw][cw][1]:
            dp[ccw+1][cw][1] = max(dp[ccw+1][cw][1], dp[ccw][cw][1] + (left[ccw+1] + l - left[ccw]) % l)
            dp[ccw][cw+1][0] = max(dp[ccw][cw+1][0], dp[ccw][cw][1] + (left[ccw] + l - right[cw+1]) % l)

ans = 0
for ccw in range(n+1):
    cw = n - ccw
    ans = max(ans, dp[ccw][cw][0], dp[ccw][cw][1])
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


l,n = li()
x = [ni() for _ in range(n)]

dp = [[[0 for _ in range(2)] for _ in range(n+1)] for _ in range(n+1)]
left = [0] + x
right = [l] + x[::-1]

for total in range(1,n+1):
    for ccw in range(total+1):
        cw = total - ccw
        if ccw == 0:
            dp[ccw][cw][1] = dp[ccw][cw-1][1] + (right[cw-1] + l - right[cw]) % l
            
        elif cw == 0:
            dp[ccw][cw][0] = dp[ccw-1][cw][0] + (left[ccw] + l - left[ccw-1]) % l
        
        else:
            dp[ccw][cw][0] = max(dp[ccw-1][cw][1] + (left[ccw] + l - right[cw]) % l,
                                 dp[ccw-1][cw][0] + (left[ccw] + l - left[ccw-1]) % l)

            dp[ccw][cw][1] = max(dp[ccw][cw-1][1] + (right[cw-1] + l - right[cw]) % l,
                                 dp[ccw][cw-1][0] + (left[ccw] + l - right[cw]) % l)
ans = 0
for ccw in range(n+1):
    cw = n - ccw
    ans = max(ans, dp[ccw][cw][0], dp[ccw][cw][1])
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
def 解():
    L,N=[int(_) for _ in input().split()]
    aX=[int(_) for _ in sys.stdin.readlines()]
    iMax = max(aX[0],L-aX[0],aX[-1],L-aX[-1])
    if 1 < N:
        for i in range(N-1):

            lN = min(i,N-i-1)
            rN = min(i+1,N-i-1)
            R1 = aX[i]+ 2*sum(aX[i-lN:i]) + 2*(rN*L-(sum(aX[i+1:i+rN+1])))

            i += 1
            lN = min(i,N-i)
            rN = min(i,N-i-1)
            R2 = (L- aX[i])+ 2*sum(aX[i-lN:i]) + 2*(rN*L-(sum(aX[i+1:i+rN+1])))

            iMax = max(R1,R2,iMax)
    print(iMax)
解()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

L, N = map(int, input().split())
x = [int(input()) for _ in range(N)]

ans = 0
for w in range(2):  # 向き
    for i in range(N):
        y = deque(x)
        b = 0
        cur = 0 if w == 0 else L
        cnt = 0
        while cnt < N:
            if cnt <= i:
                if w == 0:
                    t = y.popleft()
                    cnt += 1
                    b += t - cur
                    cur = t
                else:
                    t = y.pop()
                    cnt += 1
                    b += cur - t
                    cur = t
            else:
                if (cnt - i + w) % 2 == 1:
                    t = y.pop()
                    cnt += 1
                    b += (L - t) + cur
                    cur = t
                else:
                    t = y.popleft()
                    cnt += 1
                    b += t + (L - cur)
                    cur = t
        ans = max(ans, b)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
L, N = (int(i) for i in input().split())
X = [int(input()) for _ in range(N)]
X.insert(0, 0)

def f(L, N, X, p, l, r, d_l):
    w = 0
    for _ in range(N - (l + r)):
        if d_l:  # L
            l += 1
            w += X[l] - p
            p = X[l]
            d_l = False
        else:  # R
            r += 1
            w += L - X[-r] + p
            p = X[-r] - L
            d_l = True
    return w

X_c = [L - i for i in X]

max_l = max(X[i] + f(L, N, X, X[i], i, 0, False) for i in range(1, N+1))
max_r = max(X_c[-i] + f(L, N, X, -X_c[-i], 0, i, True) for i in range(1, N+1))
print(max(max_l, max_r))

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10000)

def evn(X,pos,N,dir,flag,cnt,dchange):
    #print(X,pos,N,dir,flag,cnt)
    if N == 1:
        #print(cnt)
        return 0
    if dir == 0:
        l = abs(X[(pos-1)%N] - X[pos])
        if (pos-1)%N == N-1:
            l = abs(M-X[(pos-1)%N]) + X[pos]
        
        #print(l)
        if X[pos] == dchange or flag:
            del X[pos]
            return l + evn(X[:],(pos-1)%(N-1),N-1,1,True,cnt+l,dchange)
        else:
            del X[pos]
            return l + evn(X[:],(pos-1)%(N-1),N-1,0,False,cnt+l,dchange)
    else:
        r = abs(X[(pos+1)%N] - X[pos])
        if (pos+1)%N == 0:
            r = X[(pos+1)%N] + abs(M-X[pos])
    
        #print(r)
        if X[pos] == dchange or flag:
            del X[pos]
            return r + evn(X[:],(pos)%(N-1),N-1,0,True,cnt+r,dchange)
        else:
            del X[pos]
            return r + evn(X[:],(pos)%(N-1),N-1,1,False,cnt+r,dchange)

M,N = list(map(int,input().split()))
X = [0]
for i in range(N):
    X.append(int(input()))

print(max(max([evn(X[:],0,N+1,1,False,0,i) for i in X[1:]]),max([evn(X[:],0,N+1,0,False,0,i) for i in X[1:]])))

Submission status: Time Limit Exceeded

Solution code:
import itertools
L,N=map(int,input().split())
tree=[]
for i in range(N):
  tree.append(int(input()))
trcp=tree
seq=(0,-1)
pat=(list(itertools.product(seq,repeat=N)))
ans=[]
tree=[]
for l in pat:
  for j in range(N):
    tree.append(trcp[j])
  t=0
  road=0
  for i in range(N):
    if l[i]==0:
      road+=tree[0]
      t=tree[0]
      del tree[0]
    else:
      road+=L-tree[-1]
      t=tree[-1]-L
      del tree[-1]
    for k in range(len(tree)):
        tree[k]=tree[k]-t 
  ans.append(road)
print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
L,N=input().split()
L,N=int(L),int(N)
X=list()
X.append(0)
for i in range(N):
    X.append(int(input()))

dp = [[[0,0] for i in range(N+1)] for j in range(N+1)]
dp[1][0][0]=X[1]
dp[0][1][1]=L-X[-1]
ans=0
for i in range(0,N+1):
    for j in range(max(0,2-i),N+1):
        if i+j > N:
            break
        if i>0:
            fromi=0
            fromj=0
            if i>1:
                fromi=X[i]-X[i-1]+dp[i-1][j][0]
            if j>0:
                fromj=dp[i-1][j][1]+X[i]+L-X[N+1-j]
            dp[i][j][0]=max(fromi,fromj)

        if j>0:
            fromi=0
            fromj=0
            if i>0:
                fromi=X[i]+L-X[N+1-j]+dp[i][j-1][0]
            if j>1:
                fromj=dp[i][j-1][1]+(X[N-j+2]-X[N-j+1])
            dp[i][j][1]=max(fromi,fromj)

ans=0
for i in range(N+1):
    #print(i,N-i,dp[i][N-i][0],dp[i][N-i][1])
    ans=max(ans,dp[i][N-i][0],dp[i][N-i][1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def cul(tree,n,l,ans,flug):
    cul=0
    p=0
    for i in range(n):
        if(i%2==flug):
            cul+=(tree[0]-p)%l
            p=tree[0]
            tree.pop(0)
        else:
            cul+=(p-tree[len(tree)-1])%l
            p=tree[len(tree)-1]
            tree.pop(len(tree)-1)
    if(cul>ans[0]):
        ans[0]=cul
l,n=[int(i) for i in input().split()]
tree=[]
p=0
ans=[0]
for i in range(n):
    tree.append(int(input()))
a=tree.copy()
for i in range(n):
    cul(a.copy(),n-i,l,ans,0)
    a.pop(0)
a=tree.copy()
for i in range(n):
    cul(a.copy(),n-i,l,ans,1)
    a.pop(len(a)-1)
print(ans[0])

Submission status: Time Limit Exceeded

Solution code:
def solve(L, N, X):
  maxLength = 0

  for i in range(N):
    sumLength = X[i]
    currentPos = X[i]
    s = i + 1
    e = N - 1
    for j in range(N - i - 1):
      if j & 1 == 1:
        sumLength += X[s] - currentPos + L
        currentPos = X[s]
        s += 1
      else:
        sumLength += currentPos - X[e] + L
        currentPos = X[e]
        e -= 1

    if maxLength < sumLength:
      maxLength = sumLength

  X = [L - X[N - i - 1] for i in range(N)]
  ccSum = [0 for i in range(N)]
  for i in range(N):
    sumLength = X[i]
    currentPos = X[i]
    s = i + 1
    e = N - 1
    for j in range(N - i - 1):
      if j & 1 == 1:
        sumLength += X[s] - currentPos + L
        currentPos = X[s]
        s += 1
      else:
        sumLength += currentPos - X[e] + L
        currentPos = X[e]
        e -= 1

    if maxLength < sumLength:
      maxLength = sumLength

  return maxLength


L, N = map(int, input().split())
X = [int(input()) for i in range(N)]

print(solve(L, N, X))

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10000)

def evn(X,pos,N,dir,flag):
    #print(X,pos,N,dir,flag)
    if N == 1:
        return 0
    if flag == False:
        l = abs(X[(pos-1)%N] - X[pos])
        if (pos-1)%N == N-1:
            #print("head l")
            l = abs(M-X[(pos-1)%N]) + X[pos]
    
        r = abs(X[(pos+1)%N] - X[pos])
        if (pos+1)%N == 0:
            #print("tail r")
            r = X[(pos+1)%N] + abs(M-X[pos])
        del X[pos]
        if l==r:
            flag == True
        #print(l,r)
        return max(l + evn(X[:],(pos-1)%(N-1),N-1, 1,flag),r + evn(X[:],(pos)%(N-1),N-1,1,flag))

    elif dir == 0:
        l = abs(X[(pos-1)%N] - X[pos])
        if (pos-1)%N == N-1:
            l = abs(M-X[(pos-1)%N]) + X[pos]
        del X[pos]
        #print(l)
        return l + evn(X[:],(pos-1)%(N-1),N-1,1,True)
    else:
        r = abs(X[(pos+1)%N] - X[pos])
        if (pos+1)%N == 0:
            r = X[(pos+1)%N] + abs(M-X[pos])
        del X[pos]
        #print(r)
        return r + evn(X[:],(pos)%(N-1),N-1,0,True)

M,N = list(map(int,input().split()))
X = [0]
for i in range(N):
    X.append(int(input()))
print(evn(X[:],0,N+1,1,False))

Submission status: Time Limit Exceeded

Solution code:
def solve(L, N, X):
  scSum = [0 for i in range(N)]
  for i in range(N):
    sumLength = X[i]
    currentPos = X[i]
    s = i + 1
    e = N - 1
    for j in range(N - i - 1):
      if j & 1 == 1:
        sumLength += X[s] - currentPos + L
        currentPos = X[s]
        s += 1
      else:
        sumLength += currentPos - X[e] + L
        currentPos = X[e]
        e -= 1

    scSum[i] = sumLength

  X = [L - X[N - i - 1] for i in range(N)]
  ccSum = [0 for i in range(N)]
  for i in range(N):
    sumLength = X[i]
    currentPos = X[i]
    s = i + 1
    e = N - 1
    for j in range(N - i - 1):
      if j & 1 == 1:
        sumLength += X[s] - currentPos + L
        currentPos = X[s]
        s += 1
      else:
        sumLength += currentPos - X[e] + L
        currentPos = X[e]
        e -= 1

    ccSum[i] = sumLength

  return max([max(scSum), max(ccSum)])


L, N = map(int, input().split())
X = [int(input()) for i in range(N)]

print(solve(L, N, X))

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10000)
def evn(X,pos,N):
    #print(X,pos,N)
    if N == 1:
        return 0
    l = abs(X[(pos-1)%N] - X[pos])
    if (pos-1)%N == N-1:
        #print("head l")
        l = abs(M-X[(pos-1)%N]) + X[pos]

    r = abs(X[(pos+1)%N] - X[pos])
    if (pos+1)%N == 0:
        #print("tail r")
        r = X[(pos+1)%N] + abs(M-X[pos])

    del X[pos]

    #print(l,r)
    # if l>r:
    #     return l + evn(X[:],(pos-1)%(N-1),N-1)
    # else:
    #     return r + evn(X[:],(pos)%(N-1),N-1)
    return max(l + evn(X[:],(pos-1)%(N-1),N-1),r + evn(X[:],(pos)%(N-1),N-1))


M,N = list(map(int,input().split()))
X = [0]
for i in range(N):
    X.append(int(input()))
print(evn(X[:],0,N+1))