Problem:


Score : 400 points

Problem Statement

Your friend gave you a dequeue D as a birthday present.

D is a horizontal cylinder that contains a row of N jewels.

The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.

In the beginning, you have no jewel in your hands.

You can perform at most K operations on D, chosen from the following, at most K times (possibly zero):

Operation A: Take out the leftmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation B: Take out the rightmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation C: Choose a jewel in your hands and insert it to the left end of D. You cannot do this operation when you have no jewel in your hand.

Operation D: Choose a jewel in your hands and insert it to the right end of D. You cannot do this operation when you have no jewel in your hand.

Find the maximum possible sum of the values of jewels in your hands after the operations.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 100

-10^7 \leq V_i \leq 10^7

Input

Input is given from Standard Input in the following format:

N K
V_1 V_2 ... V_N

Output

Print the maximum possible sum of the values of jewels in your hands after the operations.

Sample Input 1

6 4
-10 8 2 1 2 6

Sample Output 1

14

After the following sequence of operations, you have two jewels of values 8 and 6 in your hands for a total of 14, which is the maximum result.

Do operation A. You take out the jewel of value -10 from the left end of D.

Do operation B. You take out the jewel of value 6 from the right end of D.

Do operation A. You take out the jewel of value 8 from the left end of D.

Do operation D. You insert the jewel of value -10 to the right end of D.

Sample Input 2

6 4
-6 -100 50 -2 -5 -3

Sample Output 2

44

Sample Input 3

6 3
-6 -100 50 -2 -5 -3

Sample Output 3

0

It is optimal to do no operation.



Sample input:
6 4
-10 8 2 1 2 6


Sample output:
14

Submission status: Runtime Error

Solution code:
from sys import stdin
import numpy as np
# import math
# import random
# import fractions
# import sys
# sys.setrecursionlimit(100000)
# N = int(stdin.readline().rstrip().split()[0])
# A = [int(x) for x in stdin.readline().rstrip().split()]
# N, X = [int(x) for x in stdin.readline().rstrip().split()]
# S = stdin.readline().rstrip().split()[0]
N, K = [int(x) for x in stdin.readline().rstrip().split()]
V = [int(x) for x in stdin.readline().rstrip().split()]

l_list = []
L = {}
l = []
L_sum = 0
l_cnt = 0
def lf(i,s,c):
  if (i,s,c) in l_list:
    return 0
  if V[i]>0:
    s += V[i]
    c += 1
    if c in L:
      if s>L[c]:
        L[c]=s
    lf(i+1, s, c)
  if V[i]<=0:
    s += V[i]
    c += 1
    if c in L:
      if s>L[c]:
        L[c]=s
    lf(i+1, s, c)
    s -= V[i]
    c += 1
    if c in L:
      if s>L[c]:
        L[c]=s
    lf(i, s, c)

r_list = []
R = {}
r = []
R_sum = 0
r_cnt = 0
def rf(i,s,c):
  if (i,s,c) in r_list:
    return 0
  if V[i]>0:
    s += V[i]
    c += 1
    if c in R:
      if s>R[c]:
        R[c]=s
    rf(i-1, s, c)
  if V[i]<=0:
    s += V[i]
    c += 1
    if c in R:
      if s>R[c]:
        R[c]=s
    rf(i-1, s, c)
    s -= V[i]
    c += 1
    if c in R:
      if s>R[c]:
        R[c]=s
    rf(i, s, c)

lf(0,0,0)
rf(N-1,0,0)
m = 0
for i in range(N):
  if L[i] + R[N-1-i]>m:
    m = L[i] + R[N-1-i]
print(m)

Submission status: Runtime Error

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

ans = 0
for i in range(k // 2):
    for j in range(k - i - 1):
        a = v_sum[j] + v_sum[-1] - v_sum[-(k-i-j)]
        a -= sum(sorted(v[:j+1] + v[-(k-i-j):])[:i])
        ans = max(ans, a)

print(ans)

Submission status: Runtime Error

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

value = 0

for cd in range(K):
    ab = min(N, K-cd)
    for left_ab in range(ab+1):
        right_ab = ab - left_ab
        pick = V[:left_ab] + V[-right_ab:]
        pick.sort()
        neg = 0
        while True:
            if pick[neg]<0:
                neg+=1
                continue
            else:
                break
        v = sum(pick[min(neg,K):])
        value = max(value,v)
        
print(value)

Submission status: Runtime Error

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

if N==1:
	ans=max(V[0],V[-1],0)
else:
	ans=0
	for i in range(K+1):
		L=V[:i]
		L.reverse() #先頭が内側
		R=V[N-K+i:] #先頭が内側
		A=sorted(L+R) #先頭が低価値
		while True:
			flaga=0
			if L==[] and R==[]:
				break
			if len(A)==1:
				if A[0]>=0:
					break
				else:
					A.pop(0)
					break
			elif L==[]:
				C=A.copy()
				if R[0]in A: A.remove(R[0])
				if R[0] < -A[0]:
					flaga=1
					R.pop(0)
					A.pop(0)
					A.sort()
				else: A=C.copy()
			elif R==[]:
				C=A.copy()
				if L[0] in A: A.remove(L[0])
				if L[0] < -A[0]:
					flaga=1
					L.pop(0)
					A.pop(0)
					A.sort()
				else: A=C.copy()
			elif L[0]<R[0]:
				C=A.copy()
				if L[0] in A: A.remove(L[0])
				if L[0] < -A[0]:
					flaga=1
					L.pop(0)
					A.pop(0)
					A.sort()
				else: A=C.copy()
			elif L[0]>R[0]:
				C=A.copy()
				if R[0]in A: A.remove(R[0])
				if R[0] < -A[0]:
					flaga=1
					R.pop(0)
					A.pop(0)
					A.sort()
				else: A=C.copy()
			else:
				flagb=0
				for j in range(min(i,K-i)):
					C=A.copy()
					if L[0] in A: A.remove(L[0])
					if L[0] < -A[0]:
						flaga=1
						L.pop(0)
						A.pop(0)
						A.sort()
						break
					else: A=C.copy()
					C=A.copy()
					if R[0]in A: A.remove(R[0])
					if R[0] < -A[0]:
						flaga=1
						R.pop(0)
						A.pop(0)
						A.sort()
						break
					else: A=C.copy()
				if flagb: flaga=1
				elif i>=K-i:
					C=A.copy()
					if L[0] in A: A.remove(L[0])
					if L[0] < -A[0]:
						flaga=1
						L.pop(0)
						A.pop(0)
						A.sort()
					else: A=C.copy()
				else:
					C=A.copy()
					if R[0]in A: A.remove(R[0])
					if R[0] < -A[0]:
						flaga=1
						R.pop(0)
						A.pop(0)
						A.sort()
					else: A=C.copy()
			if not flaga: break
		if sum(A)>ans: ans=sum(A)


print(ans)

Submission status: Runtime Error

Solution code:
import bisect

N,K=map(int,input().split())
V=list(map(int,input().split()))

ans=0
for i in range(1,K+1):
    if i<=N:
        for j in range(i+1):
            right=V[:i-j]
            left=V[N-j:]
            right.extend(left)
            right.sort()
            index = bisect.bisect_left(right, 0)
            if index + i <= K:
                if index<len(right):
                    ans = max(ans, sum(right[index:]))
            else:
                les = K - i
                if 0<= les < len(right):
                    ans = max(ans, sum(right[les:]))
    else:
        rignt=V
        rignt.sort()
        index = bisect.bisect_left(right, 0)
        if index + i <= K:
            if index < len(right):
                ans = max(ans, sum(right[index:]))
        else:
            les = K - i
            if 0 <= les < len(right):
                ans = max(ans, sum(tmp[les:]))



print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
d = list(map(int, input().split()))
left = [0]
left_m = []
right = [0]
right_m = []
for i, l, r in zip(range(K), d, d[::-1]):
    left.append(left[i] + l)
    left_m.append(l if l < 0 else 0)
    right.append(right[i] + r)
    right_m.append(r if r < 0 else 0)
point = 0
for i in range(K):
    for j in range(K - i):
        p = K - i - j
        minus = list(sorted(left_m[:i] + right_m[:j]))
        point = max(point, left[i] + right[j] - sum(minus[:p]))
print(point)

Submission status: Runtime Error

Solution code:
import numpy as np
N, K = map(int, input().split())
V_list = list(map(int, input().split()))

def listRemove(list, val):
    result = list[:]
    result.remove(val)
    return result

def optimal_exec(tempD, tempK, hand):
    if len(tempD) == 0:
        return 0, hand

    if tempK == 1:
        left = tempD[0]
        right = tempD[-1]

        if (right < 0) and (left < 0):
            return 0, hand
        elif right > left:
            return right, hand + [right]
        else:
            return left, hand + [right]
   
    else:
        options = np.array([
            optimal_exec(tempD[:], tempK-1, hand),
            (lambda res: (res[0]+tempD[0], res[1])) (optimal_exec(tempD[1:], tempK-1, hand+[tempD[0]])),
            (lambda res: (res[0]+tempD[-1], res[1])) (optimal_exec(tempD[:-1], tempK-1, hand+[tempD[-1]]))
        ] + [
            (lambda res: (res[0]-v, res[1])) ( optimal_exec([v] + tempD, tempK-1, listRemove(hand, v)) )
            for v in hand
        ] + [
            (lambda res: (res[0]-v, res[1])) ( optimal_exec(tempD + [v], tempK-1, listRemove(hand, v)) )
            for v in hand
        ])
        
        max_i = np.argmax(options[:, 0])
        return options[max_i]

print(optimal_exec(V_list, K, [])[0])

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
ans=[0]
for i in range(K+1):
    #print(i)
    for j in range(i+1):
        if N<=j:
            temp=sorted(V)
        elif j-i!=0:
            temp=sorted(V[:j]+V[min(-1,j-i):])
        else:
            temp=sorted(V[:j])
        t=0
        for k in range(i):
            if temp[k]>=0:
                t=k+1
                break
        #print(temp,t)
        #if t==0:
        #    print(":",0)
        if t>K-i:
            #print(":",temp[K-i:])
            ans.append(sum(temp[K-i:]))
        elif (K-1-t)%2==1:
            if t>=2:
                #print(":",max(sum(temp[t-2:]),sum(temp[t:])))
                ans.append(max(sum(temp[t-2:]),sum(temp[t:])))
            else:
                #print(":",sum(temp[t:]))
                ans.append(sum(temp[t:]))
        else:
            #print(":",sum(temp[t-1:]))
            ans.append(sum(temp[t-1:]))
print(max(ans))

Submission status: Runtime Error

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

N = int(N)
K = int(K)

chance = K
v = list(int(i) for i in input().split())
j=0
count = 0

print(v)
i = 0
while (K > 0):
  if(v[i] != None):
    count = count + v[i]
    K-=1
    v[i] = None
  if(v[N-1] != None):
    count = count + v[i]
    K-=1
    v[N] = None
  i+=1
  N-=1

print(count)

Submission status: Runtime Error

Solution code:
from sys import stdin

n, k = [int(x) for x in stdin.readline().rstrip().split()]
v = list(map(int, input().split()))

l = [ [(0, [])]*(k+1) for _ in range(k+1)]

left=0
right=0
for i in range(k+1):
  left=0
  for j in range(k+1):
    if i==0 and j==0:
        continue
#    if k <= (left+right):
    if k < (i+j):
        break
    if j==0:
      item = v[(n-1)-right]
      right +=1
      l[i][j] = (l[i-1][j][0]+item,l[i-1][j][1]+[item])
      continue
    item = v[left]
    left +=1
    l[i][j] = (l[i][j-1][0]+item,l[i][j-1][1]+[item])

#for i in range(k+1):
#  print(l[i])

ans = 0
for i in range(k+1):
  for j in range(k+1):
    if k < (i+j):
      break
    value = l[i][j][0]
    if ( k != (i+j)):
        itemlist = l[i][j][1]
        itemlist.sort()
        #print(itemlist)
        for ii in range (k-(i+j)):
           if len(itemlist) <= ii:
               break
           if 0 < itemlist[ii]:
               break
           value -= itemlist[ii]
        #print(i,j,value)
    ans = max(ans, value)

print(ans)

Submission status: Runtime Error

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, log2
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N, K = MAP()
V = LIST()
max_ = 0
for j in range(K%2, K+1, 2):
	if j == 0:
		continue
	if j > N:  # N こまでしかとれない
		break
	# print("---j={}---".format(j))
	for i in range(j+1):  # jは残す数
		if (j+K)//2 >= N:
			tmp_lis = V[:]
		else:
			l = -i
			r = (j+K)//2 - i
			if l == 0 or r == -1:
				tmp_lis = V[l:r]
			else:
				tmp_lis = V[0:r] + V[l:]
		tmp_lis.sort(reverse=True)
		# print(tmp_lis)
		tmp = sum(tmp_lis[:j])
		max_ = max(max_, tmp)
		if (j == N or j == N-1) and K > N:  # とれる個数が多いとき
			for i in range(K-N):
				# print(tmp_lis)
				tmp_lis.pop()
				tmp = sum(tmp_lis)
				max_ = max(max_, tmp)
print(max_)

Submission status: Runtime Error

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

ans = 0
for i in range(k // 2):
    a = v_sum[-(k-i)] - sum(sorted(v[-(k-i):])[:i])
    ans = max(ans, a)
    a = v_sum[k-i] - sum(sorted(v[k-i])[:i])
    ans = max(ans, a)
    for j in range(k - i):
        a = v_sum[j] + v_sum[-1] - v_sum[-(k-i-j)]
        a -= sum(sorted(v[:j+1] + v[-(k-i-j):])[:i])
        ans = max(ans, a)

print(ans)

Submission status: Runtime Error

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

slice_L = [list(sorted(v[:i])) for i in range(N + 1)]
sum_L = [sum(slice_L[i]) for i in range(N + 1)]

slice_R = [list(sorted(v[N - 1 - i:])) for i in range(-1, N)]
sum_R = [sum(slice_R[i]) for i in range(N + 1)]
# print(slice_L)
# print(slice_R)

ans = 0
for put, pick in enumerate(tuple(range(K, 0, -1)), 0):
    for left in range(pick + 1):
        m_put = put
        right = pick - left
        t = sum(slice_L[left]) + sum(slice_R[right])
        sl_i = 0
        sr_i = 0
        # print(m_put)
        while m_put > 0:
            # print(right, sr_i, slice_R[right])
            if sl_i == left:
                if sr_i == right: break
                t -= slice_R[right][sr_i]
                sr_i += 1
            elif sr_i == right:
                t -= slice_L[left][sl_i]
                sl_i += 1
            elif slice_L[left][sl_i] < slice_R[right][sr_i]:
                t -= slice_L[left][sl_i]
                sl_i += 1
            elif slice_L[left][sl_i] > slice_R[right][sr_i]:
                # print('test')
                t -= slice_R[right][sr_i]
                sr_i += 1
            else:
                if sl_i + 1 == left:
                    if sr_i == right: break
                    t -= slice_R[right][sr_i]
                    sr_i += 1
                elif sr_i + 1 == right:
                    t -= slice_L[left][sl_i]
                    sl_i += 1
                else:
                    flg = False
                    k = 0
                    while slice_L[left][sl_i + k] == slice_R[right][sr_i + k]:
                        k += 1
                        if sl_i + k == left:
                            t -= slice_R[right][sr_i]
                            sr_i += 1
                            flg = True
                            break
                        elif sr_i + k == right:
                            t -= slice_L[left][sl_i]
                            sl_i += 1
                            flg = True
                            break
                    if not flg:
                        if sl_i + k == left and sr_i + k == right:
                            t -= slice_L[left][sl_i]
                            sl_i += 1
                        elif slice_L[left][sl_i + k] < slice_R[right][sr_i + k]:
                            t -= slice_L[left][sl_i]
                            sl_i += 1
                        elif slice_L[left][sl_i + k] > slice_R[right][sr_i + k]:
                            t -= slice_R[right][sr_i]
                            sr_i += 1
            m_put -= 1
        # print(pick, left, right, t, slice_R[right], slice_L[left])
        ans = max(ans, t)
print(ans)

Submission status: Runtime Error

Solution code:
N,K=map(str,raw_input().split())
V = list(map(float,raw_input().split()))

q =0
v =0
de = []
de.append(0)
Vr=[]
Vr.append(0)
for i in range(K):
    if q==N:
        break
    if V[q]>=0 and V[q]>=de[0]:
        v+=V[q]
        Vr.append(v)
        q+=1
    elif V[q]>=0 and V[q]<de[0]:
        v+=de[0]
        de[0]=0
        de = sorted(de,reverse=True)
        Vr.append(v)
    elif V[q]<0 and de[0]==0:
        de.append(abs(V[q]))
        sorted(de,reverse=True)
        v-=de[0]
        de = sorted(de,reverse=True)
        Vr.append(v)
        q+=1
    elif abs(V[q])>de[0]:
        v+=de[0]
        de[0]=0
        de = sorted(de,reverse=True)
        Vr.append(v)
    else:
        de.append(abs(V[q]))
        v-=abs(V[q])
        de = sorted(de,reverse=True)
        q+=1
q =0
v =0
de = []
de.append(0)
Vl=[]
Vl.append(0)
for i in range(K):
    if q==N:
        break
    if V[N-1-q]>=0 and V[N-1-q]>=de[0]:
        v+=V[N-1-q]
        Vr.append(v)
        q+=1
    elif V[N-1-q]>=0 and V[N-1-q]<de[0]:
        v+=de[0]
        de[0]=0
        de = sorted(de,reverse=True)
        Vr.append(v)
    elif V[N-1-q]<0 and de[0]==0:
        de.append(abs(V[N-1-q]))
        sorted(de,reverse=True)
        v-=de[0]
        de = sorted(de,reverse=True)
        Vr.append(v)
        q+=1
    elif abs(V[N-1-q])>de[0]:
        v+=de[0]
        de[0]=0
        de = sorted(de,reverse=True)
        Vr.append(v)
    else:
        de.append(abs(V[N-1-q]))
        v-=abs(V[N-1-q])
        de = sorted(de,reverse=True)
        q+=1
if len(Vr)<K+1:
    for i in range(K+1-len(Vr)):
        Vr.append(0)
if len(Vl)<K+1:
    for i in range(K+1-len(Vl)):
        Vl.append(0)
for i in range(K+1):
    Vr[i]+=Vl[K-i]
print max(Vr)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
v = list(map(int, input().split()))
w = []
dp = [0] * k

for i in range(k - 1):
    if v and w:
        if max(v[0], v[-1], min(w)) == v[0]:
            dp[i + 1] = dp[i] + v[0]
            w.append(v.pop(0))
        elif max(v[0], v[-1], min(w)) == v[-1]:
            dp[i + 1] = dp[i] + v[-1]
            w.append(v.pop())
        elif max(v[0], v[-1], min(w)) == min(w):
            dp[i + 1] = dp[i] - min(w)
            if v[0] > v[-1]:
                v.append(w.remove(min(w)))
            else:
                v.insert(0, w.remove(min(w)))
    elif v and not w:
        if v[0] > v[-1]:
            dp[i + 1] = dp[i] + v[0]
            w.append(v.pop(0))
        else:
            dp[i + 1] = dp[i] + v[-1]
            w.append(v.pop())
    else:
        dp[i + 1] = dp[i] - min(w)
        v.append(w.remove(min(w)))

print(dp[k - 1])

Submission status: Runtime Error

Solution code:


def get_data(data_left, nokori):
    # print(data_left, nokori)
    while 1:
        if len(data_left) == 0:
            break
        if data_left[-1] <= 0:
            data_left.pop(-1)
            nokori += 1
        else:
            break

    # print(data_left, nokori)

    while nokori > 0:
        if len(data_left) == 0:
            break
        min_data = min(data_left)
        if min_data < 0:
            data_left.pop(data_left.index(min_data))
            nokori -= 1
        else:
            break
        # print('uuu', data_left)

    # print(data_left)

    while 1:
        if len(data_left) == 0:
            break
        saigo = data_left[-1]
        min_data = min(data_left)

        if saigo + min_data < 0:
            data_left.pop(-1)

            if len(data_left) == 0:
                nokori += 1
                break
            if min_data not in data_left:
                nokori += 1
            else:
                # print(data_left.index(min_data))
                data_left.pop(data_left.index(min_data))
        else:
            break

    return nokori, data_left

def main():

    num_houseki, num_sousa = map(int, input().split())
    data = list(map(int, input().split()))


    ans = 0


    # dp = defaultdict(int)

    for i in range(num_sousa + 1):

        nokori = 0
        left_ind = min(i, num_houseki)
        nokori += i - left_ind
        righ_ind = max(left_ind, num_houseki - num_sousa + i)
        nokori += num_sousa - i - num_houseki + righ_ind
        data_left = data[:left_ind]
        data_right = data[righ_ind:]

        # print('<><<><<><')
        # print(data_left)
        # print(data_right)

        pre_left = data_left.copy()
        pre_right = data_right.copy()

        nokori, data_left = get_data(data_left, nokori)
        nokori, data_right = get_data(data_right[::-1], nokori)
        data_right = data_right[::-1]

        nokori, data_left = get_data(data_left, nokori)
        nokori, data_right = get_data(data_right[::-1], nokori)
        data_right = data_right[::-1]

        nokori, data_left = get_data(data_left, nokori)
        nokori, data_right = get_data(data_right[::-1], nokori)
        data_right = data_right[::-1]

        nokori, data_left = get_data(data_left, nokori)
        nokori, data_right = get_data(data_right[::-1], nokori)
        data_right = data_right[::-1]



        # print('----')
        # print(data_left)
        # print(data_right)

        kari = sum(data_right) + sum(data_left)
        if kari > ans:
            ans = kari

    print(ans)







if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
ans=[0]
for i in range(K+1):
    #print(i)
    for j in range(i+1):
        if N<=j:
            temp=sorted(V)
        elif j-i!=0:
            temp=sorted(V[:j]+V[max(i,j-i):])
        else:
            temp=sorted(V[:j])
        t=0
        for k in range(i):
            if temp[k]>=0:
                t=k+1
                break
        #print(temp,t)
        #if t==0:
        #    print(":",0)
        if t>K-i:
            #print(":",temp[K-i:])
            ans.append(sum(temp[K-i:]))
        elif (K-1-t)%2==1:
            if t>=2:
                #print(":",max(sum(temp[t-2:]),sum(temp[t:])))
                ans.append(max(sum(temp[t-2:]),sum(temp[t:])))
            else:
                #print(":",sum(temp[t:]))
                ans.append(sum(temp[t:]))
        else:
            #print(":",sum(temp[t-1:]))
            ans.append(sum(temp[t-1:]))
print(max(ans))

Submission status: Runtime Error

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

left = np.cumsum([0] + v)
right = np.cumsum([0] + v[::-1])

results = []
for backn in range(k + 1):
    at = k - backn

    t = min(n, at)
    # print('----', backn, t)
    for shift in range(t + 1):
        p = v[:t - shift] + v[n - shift:]
        # print(v[:t - shift], v[n - shift:])
        p.sort()
        value = sum(p[backn:])
        results.append(value)
print(max(max(results)), 0)

Submission status: Runtime Error

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, log2
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N, K = MAP()
V = LIST()
max_ = 0
for j in range(K%2, K+1, 2):
	if j == 0:
		continue
	if j > N:  # N こまでしかとれない
		break
	# print("---j={}---".format(j))
	for i in range(j+1):  # jは残す数
		if (j+K)//2 >= N:
			tmp_lis = V[:]
		else:
			l = -i
			r = (j+K)//2 - i
			if l == 0 or r == -1:
				tmp_lis = V[l:r]
			else:
				tmp_lis = V[0:r] + V[l:]
		tmp_lis.sort(reverse=True)
		# print(tmp_lis)
		tmp = sum(tmp_lis[:j])
		max_ = max(max_, tmp)
		if (j == N or N-1) and K > N:  # とれる個数が多いとき
			for i in range(K-N):
				# print(tmp_lis)
				tmp_lis.pop()
				tmp = sum(tmp_lis)
				max_ = max(max_, tmp)
print(max_)

Submission status: Runtime Error

Solution code:
from copy import copy
from bisect import bisect_left

n,k = (int(num) for num in input().split())
v = [int(num) for num in input().split()]

def p(k,v):
    ret = 0
    for i in range(k+1):
        vt = copy(v)
        vt = vt[:i]
        vt.sort(reverse=True)
        t = 0 
        #print(i,len(vt))
        for j in range(i):
            t += vt[j]
            if j+1 >= i*2-k and t > ret:
                ret = t
    return ret

def length(v):
    ret = 0
    for num in v:
        if num < 0:
            ret += 2
        else:
            ret += 1
    return ret
            
vr = copy(v)
vr.reverse()
ans = 0

k = min(k,length(v))
for i in range(k+1):
    t = p(i,v) + p(k-i,vr)
    #print(i,p(i,v),p(k-i,vr),t)
    if t > ans:
        ans = t
print(ans)

Submission status: Runtime Error

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

import copy

import sys

INT_MIN = -1 * sys.maxsize

import bisect

def dfs(k, v_q, v_plus, v_minus):
    v_p_sum = sum(v_plus)
    #if k == 0:
    #    return v_p_sum + sum(v_minus)
    #c = INT_MIN
    if k < len(v_minus):
        #v_minus = sorted(v_minus)
        c = v_p_sum + sum(v_minus[k:])
        return c
    
    
    v_q_left = copy.copy(v_q)
    l = v_q_left.popleft()
    if l >= 0:
        a = dfs(k-1, v_q_left, v_plus[:]+[l], v_minus[:])
    else:
        tmp = v_minus[:]
        bisect.insort(tmp, l)
        a = dfs(k-1, v_q_left, v_plus[:], tmp)
    
    v_q_right = copy.copy(v_q)
    r = v_q_right.pop()
    if r >= 0:
        b = dfs(k-1, v_q_right, v_plus[:]+[r], v_minus[:])
    else:
        tmp = v_minus[:]
        bisect.insort(tmp, r)
        b = dfs(k-1, v_q_right, v_plus[:], tmp)
    
    return max([a, b, v_p_sum])
    


from collections import deque
v_q = deque(V)

ans = dfs(K, v_q, [], [])
print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
q=[[0,0,n-1,[]]]
qq=[]
ans=0
a=min(k,n-1)
while len(q)>0:
  #print(q)
  qi=q.pop()
  #print(qi)
  
  if qi[0]==a or qi[1]==qi[2]+1:
    continue
  q+=[[qi[0]+1,qi[1]+1,qi[2],qi[3]+[v[qi[1]]]]]
  q+=[[qi[0]+1,qi[1],qi[2]-1,qi[3]+[v[qi[2]]]]]
  qq+=[[qi[0]+1,qi[1]+1,qi[2],qi[3]+[v[qi[1]]]]]
  qq+=[[qi[0]+1,qi[1],qi[2]-1,qi[3]+[v[qi[2]]]]]
  
if k>=n:
  qq+=[[n,v]]
  
  
while len(qq)>0:
  qi=qq.pop()
  ans=max(ans,sum(qi[3]))
  if qi[0]==k:
    continue
  if len(qi[3])==0:
    continue
  if len(qi[3])==1:
    continue
  #print(qi)
  qi[3].remove(min(qi[3]))
  qq+=[[qi[0]+1,qi[1],qi[2],qi[3]]]
  #print(qi)
print(ans)

Submission status: Runtime Error

Solution code:
import math

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

val2 = [val[n-i-1] for i in range(n)]
#print(val2)

valcase = []
valcase.append([[],[]])

for ii in range(k):
    i=ii+1
    valcase.append([[],[]])
    for j in range(i):
        valtemp=val[j]
        if(valtemp>=0):
            valcase[i][1].append(valtemp)
        else:
            valcase[i][0].append(valtemp)
    list.sort(valcase[i][0])
    list.sort(valcase[i][1],reverse=True)
#print(valcase)

left = [[] for i in range(k+1)]

for i in range(k):
    j=i+1
    left[j] = [[] for ii in range((j+1)//2)]
    
#print(left)

for ii in range(k):
    i=ii+1
    if(i==1):
        left[i][0]=val[0]
        continue
    for j in range((i+1)//2):
        if(j==0):
            left[i][0] = left[i-1][0] + val[i-1]
        else:
            if(len(valcase[i-j-1][0])<j):
                left[i][j] = left[i-1][j-1]
            else:
                left[i][j] = left[i-1][j-1] - valcase[i][0][j-1]

#print("left")
#print(left)
left2 = left

val=val2

valcase = []
valcase.append([[],[]])

for ii in range(k):
    i=ii+1
    valcase.append([[],[]])
    for j in range(i):
        valtemp=val[j]
        if(valtemp>=0):
            valcase[i][1].append(valtemp)
        else:
            valcase[i][0].append(valtemp)
    list.sort(valcase[i][0])
    list.sort(valcase[i][1],reverse=True)
#print(valcase)

left = [[] for i in range(k+1)]

for i in range(k):
    j=i+1
    left[j] = [[] for ii in range((j+1)//2)]
    
#print(left)

for ii in range(k):
    i=ii+1
    if(i==1):
        left[i][0]=val[0]
        continue
    for j in range((i+1)//2):
        if(j==0):
            left[i][0] = left[i-1][0] + val[i-1]
        else:
            if(len(valcase[i-j-1][0])<j):
                left[i][j] = left[i-1][j-1]
            else:
                left[i][j] = left[i-1][j-1] - valcase[i][0][j-1]

#print("right")
#print(left)

right=left
left=left2
left[0].append(0)
right[0].append(0)

maxim = 0

for i in range(k+1):
    for j in range(k-i+1):
    
        temp=max(left[i])+max(right[j])
        if(maxim<temp):
            maxim=temp
            
print(maxim)

Submission status: Runtime Error

Solution code:
import numpy as np
N, K = map(int, input().split())
V_list = list(map(int, input().split()))

def listRemove(list, val):
    result = list[:]
    result.remove(val)
    return result

def handleExecResult(res, v):
    return 

def optimal_exec(tempD, tempK, hand):
    if len(tempD) == 0:
        return 0, hand

    if tempK == 1:
        left = tempD[0]
        right = tempD[-1]

        if (right < 0) and (left < 0):
            return 0, hand
        elif right > left:
            return right, hand + [right]
        else:
            return left, hand + [right]
   
    else:
        options = np.array([
            optimal_exec(tempD[:], tempK-1, hand),
            (lambda res: (res[0]+tempD[0], res[1])) (optimal_exec(tempD[1:], tempK-1, hand+[tempD[0]])),
            (lambda res: (res[0]+tempD[-1], res[1])) (optimal_exec(tempD[:-1], tempK-1, hand+[tempD[-1]]))
        ] + [
            (lambda res: (res[0]-v, res[1])) ( optimal_exec([v] + tempD, tempK-1, listRemove(hand, v)) )
            for v in hand
        ] + [
            (lambda res: (res[0]-v, res[1])) ( optimal_exec(tempD + [v], tempK-1, listRemove(hand, v)) )
            for v in hand
        ])
        
        max_i = np.argmax(options[:, 0])
        return options[max_i]

print(optimal_exec(V_list, K, [])[0])