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:
import copy

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

mx = 0
for num_out in range(k+1):
	num_ret = k-num_out
	if num_out > n:
		out = copy.deepcopy(v).sort()
		for ret_v in out[:num_ret]:
			if ret_v < 0:
				ret_value += ret_v
			else:
				break
		val = sum(out) - ret_value
		if val > mx:
			mx = val
		continue

	for num_out_l in range(num_out+1):
		num_out_r = num_out - num_out_l
		out = v[:num_out_l] + v[n-num_out_r:]
		out.sort()
		ret_value = 0
		for ret_v in out[:num_ret]:
			if ret_v < 0:
				ret_value += ret_v
			else:
				break
		val = sum(out) - ret_value
		if val > mx:
			mx = val
			
print(mx)

Submission status: Runtime Error

Solution code:
import sys
input=sys.stdin.readline
from collections import deque
from heapq import heappush,heappop
import re

def int_raw():
    return int(input())
 
def ss_raw():
    return input().split()
 
def ints_raw():
    return tuple(map(int, ss_raw()))


def main():
    N ,K = ints_raw()
    Vs = ints_raw()
    leftSum = [0]
    leftNegas = [[]]
    for v in Vs:
        leftSum.append(leftSum[-1]+v)
        neoNega = leftNegas[-1]
        if v<0:
            neoNega = neoNega+[v]
            neoNega.sort()
        leftNegas.append(neoNega )


    rightSum = [0]
    rightNegas = [[]]
    for v in Vs[::-1]:
        rightSum.append(rightSum[-1]+v)
        neoNega = rightNegas[-1]
        if v<0:
            neoNega = rightNegas[-1]+[v]
            neoNega.sort()
        rightNegas.append(neoNega )

    ans = 0
    for left_k in range(K+1):
        left_total = 0
        left_n = 0
        for n in range(left_k+1):
            tmp = leftSum[n] - (sum(leftNegas[n]) if len(leftNegas[n])+n<=left_k else sum(leftNegas[n][:left_k-n]))
            if left_total < tmp:
                left_total = tmp
                left_n = n
        right_total = 0
        right_n = 0
        for n in range(min(K-left_k+1,N-left_n+1)):
            tmp = rightSum[n] - (sum(rightNegas[n]) if len(rightNegas[n])+n<=K-left_k else sum(rightNegas[n][:K-left_k-n]))
            if right_total < tmp:
                right_total = tmp
                right_n = n
        ans = max(ans,left_total+right_total)
    return ans

print(main())

Submission status: Runtime Error

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

value = max_value = 0
for j in range(K//2):
    for i in range(K-j+1):
        if i == K-j:
            value = V[:K-j]
        else:
            value = V[:i]+V[-(K-j-i):]
        value.sort()
        
        if value[j] > 0:
            s = sum([i for i in value if i>0])
        else:
            s = sum(value[j:])
                
        if  s > max_value:
            max_value = s

print(max_value)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
V = [int(i) for i in input().split()]
L = [0] * (N+1)
R = [0] * (N+1)
L_m = [[] for _ in range(N+1)]
R_m = [[] for _ in range(N+1)]

for i in range(1, N+1):
    L[i] = L[i-1] + V[i-1]
    R[i] = R[i-1] + V[-i]
    L_m[i] = L_m[i-1].copy()
    R_m[i] = R_m[i-1].copy()
    if V[i-1] < 0:
        L_m[i].append(V[i-1])
    if V[-i] < 0:
        R_m[i].append(V[-i])

ans = 0

for i in range(K+1):    # 消せるマイナスの数
    for l in range(K+1-i):
        r = K - i - l
        if l + r > N or r < 0:
            break
        M = L_m[l] + R_m[r]
        M.sort()
        if len(M) >= i:
            m = sum(M[:i])
            a = L[l] + R[r] - m
            ans = max(ans, a)

print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
l = [0]
for i in range(1, K + 1): #左に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        if j > i:
            break
        #print("j=",j)
        a = []
        for m in range(i - j):
            a.append(V[m])
        a.sort()
        s = 0
        for m in range(i - j):
            if m >= j or a[m] >= 0:
                s += a[m]
        b = max(b, s)
    #print("b=",b)
    l.append(max(b, l[-1]))
#print(l)
r = [0]
for i in range(1, K + 1): #右に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        if j > i:
            break
        #print("j=",j)
        a = []
        for m in range(N - i + j, N):
            a.append(V[m])
        #print("s=",s)
        a.sort()
        s = 0
        for m in range(i - j):
            if m >= j or a[m] >= 0:
                s += a[m]
        b = max(b, s)
    #print("b=",b)
    r.append(max(b, r[-1]))
#print(r)
ans = 0
for i in range(K + 1):
    ans = max(ans, l[i] + r[K - i])
print(ans)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
input = sys.stdin.readline

N, K  = map(int, input().split())
L = deque([int(v) for v in input().split()])
ans = 0

def bfs(count, point):
    global ans
    ans = max(ans, point)
    
    if count - 1 >= 0:
        left = L.popleft()
        bfs(count - 1, point + left)
        L.appendleft(left)
        
    if count - 1 >= 0:
        right = L.pop()
        bfs(count - 1, point + right)
        L.append(right)
        
    if count - 2 >= 0:
        left = L.popleft()
        bfs(count - 2, point)
        L.appendleft(left)
        
    if count - 2 >= 0:
        right = L.pop()
        bfs(count - 2, point)
        L.append(right)


bfs(K, 0)
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,[]]]
ans=0
while len(q)>0:
  #print(q)
  qi=q.pop()
  #print(qi)
  ans=max(ans,sum(qi[3]))
  if qi[0]==k:
    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]]]]]
  if len(qi[3])==0:
    continue
  if len(qi[3])==1:
    q+=[[qi[0]+1,qi[1],qi[2],[]]]
    continue
  #print(qi)
  qi[3].remove(min(qi[3]))
  q+=[[qi[0]+1,qi[1],qi[2],qi[3]]]
  #print(qi)
print(ans)

Submission status: Runtime Error

Solution code:
N, K = list(map(int, input().split()))
Vs = list(map(int, input().split()))
Length = len(Vs)

maxv = 0

for i in range(K):
    if K // 2 >= i:
        count = K - i
        for hoge in range(count):
            left = count
            right = 0
            for m in range(count):
                temp = sorted(Vs[:left] + Vs[Length - right:])
                for o in range(i):
                    temp.pop(0)
                sumv = sum(temp)
                left -= 1
                right += 1
                if sumv > maxv:
                    maxv = sumv

print(maxv)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
ls,lm,rs,rm=[0],[[0 for i in range(k+1)]for i in range(n+1)],[0],[[0 for i in range(k+1)]for i in range(n+1)]
v=list(map(int,input().split()))
ld=[]
rd=[]
for i in range(n):
    ls.append(ls[-1]+v[i])
    if v[i]<0:
        ld.append(v[i])
        ld=sorted(ld)
    for j in range(1,k+1):
        if j-1<len(ld):
            lm[i+1][j]=lm[i+1][j-1]+ld[j-1]
        else:
            lm[i+1][j]=lm[i+1][j-1]
    ii=n-i-1
    rs.append(rs[-1]+v[ii])
    if v[ii]<0:
        rd.append(v[ii])
        rd=sorted(rd)
    for j in range(1,k+1):
        if j-1<len(rd):
            rm[i+1][j]=rm[i+1][j-1]+rd[j-1]
        else:
            rm[i+1][j]=rm[i+1][j-1]


mx=-9999999999
for x in range(k+1):
    for y in range(x,k+1):
        for z in range(y,k+1):
            for w in range(z,k+1):
                a,b,c,d=x,y-x,z-y,w-z
                if a>=b and c>=d and len(lm)>b and len(rm)>d and ls[a]-lm[a][b]+rs[c]-rm[c][d]>mx:
                    # print(a,b,c,d,ls[a],lm[a][b],rs[c],rm[c][d],ls[a]+lm[a][b]+rs[c]+rm[c][d])
                    mx=ls[a]-lm[a][b]+rs[c]-rm[c][d]
print(mx)

Submission status: Runtime Error

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

rs = [0]
def check(k, v, current):
	global rs
	rs += [sum(current)]
	if 0 == k:
		return
	else:
		if current:
			i = current.index(min(current))
			check(k - 1, v + [min(current)], current[:i] + current[i + 1:])
			check(k - 1, [min(current)] + v, current[:i] + current[i + 1:])
		check(k - 1, v[1:], current + [v[0]])
		check(k - 1, v[:-1], current + [v[-1]])
		return

check(K, V, [])

print(max(rs))

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
l = [0]
for i in range(1, K + 1): #左に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        #print("j=",j)
        a = []
        for m in range(i - j):
            a.append(V[m])
        a.sort()
        s = 0
        for m in range(i - j):
            if m >= j or a[m] >= 0:
                s += a[m]
        b = max(b, s)
    #print("b=",b)
    l.append(max(b, l[-1]))
#print(l)
r = [0]
for i in range(1, K + 1): #右に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        #print("j=",j)
        a = []
        for m in range(N - i + j, N):
            a.append(V[m])
        #print("s=",s)
        a.sort()
        s = 0
        for m in range(i - j):
            if m >= j or a[m] >= 0:
                s += a[m]
        b = max(b, s)
    #print("b=",b)
    r.append(max(b, r[-1]))
#print(r)
ans = 0
for i in range(K + 1):
    ans = max(ans, l[i] + r[K - i])
print(ans)

Submission status: Runtime Error

Solution code:
import sys
# gcd
from fractions import gcd
# 切り上げ，切り捨て
# from math import ceil, floor
# リストの真のコピー（変更が伝播しない）
# from copy import deepcopy
# 累積和。list(accumulate(A))としてAの累積和
from itertools import accumulate
# l = ['a', 'b', 'b', 'c', 'b', 'a', 'c', 'c', 'b', 'c', 'b', 'a']
# S = Counter(l)  # カウンタークラスが作られる。S=Counter({'b': 5, 'c': 4, 'a': 3})
# print(S.most_common(2))  # [('b', 5), ('c', 4)]
# print(S.keys())  # dict_keys(['a', 'b', 'c'])
# print(S.values())  # dict_values([3, 5, 4])
# print(S.items())  # dict_items([('a', 3), ('b', 5), ('c', 4)])
from collections import deque
# import math
# from functools import reduce
#
# input関係の定義
# fin = open('in_3.txt', 'r')
# sys.stdin = fin
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().rstrip().split())
def lmi(): return list(map(int, input().rstrip().split()))
def li(): return list(input().rstrip())
# template


def iterate_tokens():
    for line in sys.stdin:
        for word in line.split():
            yield word


if __name__ == '__main__':

    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    V = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"

    # write code
    left = [-10 ** 9] * (K+10)
    right = [-10 ** 9] * (K + 10)
    left[0] = 0
    right[0] = 0
    left[1] = V[0]
    right[1] = V[-1]
    for i in range(2, N+1):
        tmp_max = 0
        for j in range(i // 2, i):
            tmp_V = V[:j]
            tmp_V.sort()
            if tmp_max < sum(tmp_V[i - 2 * j:]):
                tmp_max = sum(tmp_V[i - 2 * j:])
        # print(tmp_max)
        left[i] = tmp_max

    for i in range(2, N+1):
        tmp_max = 0
        for j in range(i // 2, i):
            tmp_V = V[-j:]
            tmp_V.sort()
            if tmp_max < sum(tmp_V[i - 2 * j:]):
                tmp_max = sum(tmp_V[i - 2 * j:])
        # print(tmp_max)
        right[i] = tmp_max
    ans = []
    # print(left)
    # print(right)
    for j in range(0, min(N, K) + 1):
        tmp_ans = -10**9
        for i in range(j+1):
            if tmp_ans < left[i] + right[j - i]:
                tmp_ans = left[i] + right[j - i]
        ans.append(tmp_ans)
    print(max(ans))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
ma=0
for i in range(k//2+1):
     pick=min(k-i,n)
     for j in range(pick+1):
          if j==0:
               l=v[:pick]
               al=l
          elif j==pick:
               r=v[-pick:]
               al=r
          else:
               l=v[:pick-j]
               r=v[-j:]
               al=l+r
          for rem in range(i):
               al.remove(min(al))
          ma=max(ma,sum(al))
print(ma)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
l = [0]
for i in range(1, K + 1): #左に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        #print("j=",j)
        a = V[0:i - j]
        a.sort()
        s = 0
        for m in range(i - j):
            if m >= j or a[m] >= 0:
                s += a[m]
        b = max(b, s)
    #print("b=",b)
    l.append(max(b, l[-1]))
#print(l)
r = [0]
for i in range(1, K + 1): #右に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        #print("j=",j)
        a = V[N - i + j:N]
        s = sum(a)
        #print("s=",s)
        a.sort()
        a.sort()
        s = 0
        for m in range(i - j):
            if m >= j or a[m] >= 0:
                s += a[m]
        b = max(b, s)
    #print("b=",b)
    r.append(max(b, r[-1]))
#print(r)
ans = 0
for i in range(K + 1):
    ans = max(ans, l[i] + r[K - i])
print(ans)

Submission status: Runtime Error

Solution code:
import sys
# gcd
from fractions import gcd
# 切り上げ，切り捨て
# from math import ceil, floor
# リストの真のコピー（変更が伝播しない）
# from copy import deepcopy
# 累積和。list(accumulate(A))としてAの累積和
from itertools import accumulate
# l = ['a', 'b', 'b', 'c', 'b', 'a', 'c', 'c', 'b', 'c', 'b', 'a']
# S = Counter(l)  # カウンタークラスが作られる。S=Counter({'b': 5, 'c': 4, 'a': 3})
# print(S.most_common(2))  # [('b', 5), ('c', 4)]
# print(S.keys())  # dict_keys(['a', 'b', 'c'])
# print(S.values())  # dict_values([3, 5, 4])
# print(S.items())  # dict_items([('a', 3), ('b', 5), ('c', 4)])
from collections import deque
# import math
# from functools import reduce
#
# input関係の定義
# fin = open('in_1.txt', 'r')
# sys.stdin = fin
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().rstrip().split())
def lmi(): return list(map(int, input().rstrip().split()))
def li(): return list(input().rstrip())
# template


def iterate_tokens():
    for line in sys.stdin:
        for word in line.split():
            yield word


if __name__ == '__main__':

    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    V = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"

    # write code
    left = [-10 ** 9] * (K+10)
    right = [-10 ** 9] * (K + 10)
    left[0] = 0
    right[0] = 0
    left[1] = V[0]
    right[1] = V[-1]
    for i in range(2, N+1):
        tmp_max = 0
        for j in range(i // 2, i):
            tmp_V = V[:j]
            tmp_V.sort()
            if tmp_max < sum(tmp_V[i - 2 * j:]):
                tmp_max = sum(tmp_V[i - 2 * j:])
        # print(tmp_max)
        left[i] = tmp_max

    for i in range(2, N+1):
        tmp_max = 0
        for j in range(i // 2, i):
            tmp_V = V[-j:]
            tmp_V.sort()
            if tmp_max < sum(tmp_V[i - 2 * j:]):
                tmp_max = sum(tmp_V[i - 2 * j:])
        # print(tmp_max)
        right[i] = tmp_max
    ans = []
    # print(left)
    # print(right)
    for j in range(0, N + 1):
        tmp_ans = -10**9
        for i in range(j+1):
            if tmp_ans < left[i] + right[j - i]:
                tmp_ans = left[i] + right[j - i]
        ans.append(tmp_ans)
    print(max(ans))

Submission status: Runtime Error

Solution code:
import copy

def solve(i, vs, hv):
    if i == 0:
        return sum(hv)
    re = []
    re += [solve(i - 1, vs, hv)]
    re += [solve(i - 1, vs[1:], hv + [vs[0]])]
    re += [solve(i - 1, vs[:-1], hv + [vs[-1]])]
    for hk in hv:
        if hk < 0:
            nhv=copy.deepcopy(hv)
            nhv.remove(hk)
            re += [solve(i - 1, vs + [hk], nhv)]
            re += [solve(i - 1, [hk] + vs, nhv)]
    return max(re)

n, k = map(int, input().split())
vs = list(map(int, input().split()))
print(solve(k, vs, []))

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
l = [0]
for i in range(1, K + 1): #左に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        #print("j=",j)
        a = V[0:i - j]
        s = sum(a)
        #print("s=",s)
        a.sort()
        for m in range(j):
            if a[m] >= 0:
                break
            s -= a[m]
        b = max(b, s)
    #print("b=",b)
    l.append(max(b, l[-1]))
#print(l)
r = [0]
for i in range(1, K + 1): #右に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        #print("j=",j)
        a = V[N - i + j:N]
        s = sum(a)
        #print("s=",s)
        a.sort()
        for m in range(j):
            if a[m] >= 0:
                break
            s -= a[m]
        b = max(b, s)
    #print("b=",b)
    r.append(max(b, r[-1]))
#print(r)
ans = 0
for i in range(K + 1):
    ans = max(ans, l[i] + r[K - i])
print(ans)

Submission status: Runtime Error

Solution code:
from functools import lru_cache

N,K=[int(i) for i in input().split(" ")]
V=[int(i) for i in input().split(" ")]

@lru_cache()
def value(V,k,hands):
    if k==0:
        return sum(hands)
    else:
        retval=sum(hands)
        try:
            retval=max(value(V[1::],k-1,sorted(hands+[V[0]])),retval)
        except:
            pass
        try:
            p2=value(V[:-1:],k-1,sorted(hands+[V[-1]]))
            retval=max(retval,p2)
        except:
            pass
        try:
            p3=value(V+[hands[0]],k-1,hands[1::])
            retval=max(p3,retval)
        except:
            pass
        try:
            p4=value([hands[0]]+V,k-1,hands[1::])
            retval=max(p4,retval)
        except:
            pass
        return retval

print(value(V,K,[]))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
a=[[v[:k],[]]]
for i in range(1,min(n,k)):
     l=v[:k-i]
     r=v[-i:][::-1]
     a.append([l,r])
a.append([[],v[-min(n,k):][::-1]])
ma=0
for a_ in a:
     l=a_[0]
     r=a_[1]
     su=sum(l)+sum(r)
     for i in range(k//2):
          if len(r)==0:
               l_=l.pop()
               su-=l_
               mi=min(l)
               l.remove(mi)
               su-=mi
               ma=max(ma,su)
          elif len(l)==0:
               r_=r.pop()
               su-=r_
               mi=min(r)
               r.remove(mi)
               su-=mi
               ma=max(ma,su)
          else:
               l_=l.pop()
               r_=r.pop()
               try:
                    l_mi=min(l)
               except:
                    l_mi=10**7+1
               try:
                    r_mi=min(r)
               except:
                    r_mi=10**7+1
               if l_mi>r_mi:
                    if r_mi<0:
                         r.remove(r_mi)
                         su-=r_mi
               else:
                    if l_mi<0:
                         l.remove(l_mi)
                         su-=l_mi
               if l_>r_:
                    l.append(l_)
                    su-=r_
               else:
                    r.append(r_)
                    su-=l_
               ma=max(ma,su)
print(ma)

Submission status: Runtime Error

Solution code:
read = input 
rn = lambda :list(map(int, read().split()))
# O(N^2)
n, k = rn()
V = rn() # 0 ~ n-1
best = 0
for i in range(0, n + 1): # [0, n]
    for j in range(i + 1, n+1): # [i + 1, n]
        # take [0,i), [j, n)
        yes = V[0:i] + V[j: n]
        if len(yes) > k:
            continue
        leftout = k - len(yes)
        yes.sort()
        for skip in range(len(yes)):
            if yes[skip] <0 and leftout > 0:
                leftout -= 1
            else :
                break
        if best < sum(yes[skip:]):
#             print(yes[skip:], k)
            best = sum(yes[skip:])
print(best)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
que = []
ma = 0
for i in range(K):
    P = K - i
    for p in range(P + 1):
        q1 = []
        q2 = []
        s = 0
        for j in range(p):
            if V[j] >= 0:
                s += V[j]
            else:
                q1.append(V[j])
        if len(q1) == p:
            q1 = []
        for j in range(N - 1, N - (P - p) - 1, -1):
            if V[j] >= 0:
                s += V[j]
            else:
                q2.append(V[j])
        if len(q2) == P - p:
            q2 = []

        q = sorted(q1 + q2)
        if len(q) < i:
            t = 0
        else:
            t = sum(q[i:])
        ma = max(s + t, ma)

print(ma)

Submission status: Runtime Error

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

values = []

for num_enqueue in range(k // 2):
  for num_dequeue in range(k-num_enqueue+1):
    for num_dequeue_left in range(num_dequeue+1):
      num_dequeue_right = num_dequeue - num_dequeue_left
      if num_dequeue >= n:
        dequeued = vs[:]
      else:
        dequeued = vs[:num_dequeue_left] + ([] if num_dequeue_right == 0 else vs[-num_dequeue_right:])
      dequeued_pos = [v for v in dequeued if v >= 0]
      dequeued_neg = sorted([v for v in dequeued if v < 0], reverse=True)

      for _ in range(num_enqueue):
        if dequeued_neg:
          dequeued_neg.pop()
      value = sum(dequeued_pos) + sum(dequeued_neg)
      #print(f'value={value}, enq={num_enqueue}, left={num_dequeue_left}, right={num_dequeue_right}, dequeued={dequeued}')
      values.append(value)

#print(values)
print(max(values))

Submission status: Runtime Error

Solution code:
# coding: utf-8

import sys
import math

import array
import bisect
import collections
from collections import Counter, defaultdict
import fractions
import heapq
import re

sys.setrecursionlimit(1000000)


def array2d(dim1, dim2, init=None):
    return [[init for _ in range(dim2)] for _ in range(dim1)]

def argsort(l, reverse=False):
    return sorted(range(len(l)), key=lambda i: l[i], reverse=reverse)

def argmin(l):
    return l.index(min(l))

def YESNO(ans, yes="YES", no="NO"):
    print([no, yes][ans])

II = lambda: int(input())
MI = lambda: map(int, input().split())
MIL = lambda: list(MI())
MIT = lambda: tuple(MI())
MIS = lambda: input().split()


def get(V, n):
    if n >= len(V):
        yield V
    else:
        yield V[:n]
        for i in range(1, n):
            yield V[:n-i] + V[-i:]
        yield V[-n:]


def main():
    N, K = MI()
    V = MIL()
    ans = 0

    for i in range(K//2, K + 1):
        # 左右からi個まで取る
        for vs in get(V, i):
            # K-i個まで、負を捨てる
            vs = sorted(vs)
            for j, v in enumerate(vs):
                if v >= 0: break
            ans = max(ans, sum(vs[min(K-i, j):]))
    return ans


if __name__ == "__main__":
    print(main())

Submission status: Runtime Error

Solution code:
import heapq

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

max_v = -float('inf')
for a in range(max(k,n)):
    total = 0
    minus = []
    for i in range(a):
        total += vs[i]
        if vs[i] < 0:
            heapq.heappush(minus, vs[i])
    for b in range(max(k-a,n-a)):
        c = k - a - b
        if c < 0:
            break
        h = minus[:]
        t = total
        for i in range(b):
            t += vs[n-1-i]
            if vs[n-1-i] < 0:
                heapq.heappush(h, vs[n-1-i])
        for i in range(c):
            if h:
                v = heapq.heappop(h)
                t -= v
        max_v = max(max_v, t)

print(max_v)

Submission status: Runtime Error

Solution code:

def main():
    buf = input()
    buflist = buf.split()
    N = int(buflist[0])
    K = int(buflist[1])
    buf = input()
    buflist = buf.split()
    V = list(map(int, buflist))
    max_value = 0
    for i in range(K+1):
        push_limit = K - i
        for j in range(i+1):
            jewel = []
            for k in range(-i+j, j):
                jewel.append(V[k])
            jewel = list(sorted(jewel))
            value = sum(jewel)
            for k in range(push_limit):
                if k >= len(jewel):
                    break
                if jewel[k] < 0:
                    value += -jewel[k]
                else:
                    break
            if value > max_value:
                max_value = value
    print(max_value)


if __name__ == '__main__':
    main()