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:
# python 3.4.3
import sys
input = sys.stdin.readline

# -------------------------------------------------------------
# library
# -------------------------------------------------------------



# -------------------------------------------------------------
# main
# -------------------------------------------------------------
from collections import deque
import heapq

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

ans = 0

maxPop = min(N,K)
# 左popする回数
for li in range(maxPop+1):
    # 右popする回数
    for ri in range(maxPop+1-li):
        # 初期化
        D = deque(V)
        jew = [] # 手持ちの宝石

        # pushの最大値
        maxPush = maxPop - (ri+li)
        # 左popする
        for i in range(li):
            jew.append(D.popleft())
        # 右popする
        for i in range(li):
            jew.append(D.popright())
        # 価値順にソート
        jew.sort()
        # push最大値の回数まで、負の価値の宝石をpushする（手持ちの価値を0にする）
        for i in range(min(maxPush, len(jew))):
            if jew[i] < 0:
                jew[i] = 0
        # 合計
        ans = max(ans,sum(jew))

print(ans)

Submission status: Runtime Error

Solution code:
K = int(input())

lunlun = [1,2,3,4,5,6,7,8,9]
p = 0

def lunlun_generator(now_lunlun):
    last = now_lunlun%10
    if last-1>=0:
        yield 10*now_lunlun+last-1
    yield 10*now_lunlun+last
    if last+1<=9:
        yield 10*now_lunlun+last+1 

while 1:
    for new_lunlun in lunlun_generator(lunlun[p]):
       lunlun.append(new_lunlun)

    p += 1
    if p == K:
        break

print(lunlun[p-1])

Submission status: Runtime Error

Solution code:
mod = 10 ** 9 + 7
from collections import deque
import heapq


def iip(listed):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret


def main():
    r = solve()
    print(r)


def solve():
    N, K = iip(False)
    V = iip(False)

    gsize = N+1

    dp1 = [[None for i in range(gsize)] for i in range(gsize)]
    dp1[0][0] = 0
    for i, value in enumerate(V, 1):
        for j in range(gsize):
            if dp1[i-1][j] is not None:
                dp1[i][j] = dp1[i-1][j] + value

            v = dp1[i-1][j-1]
            if j >= 1 and dp1[i-1][j-1] is not None:
                vv = dp1[i][j]
                if vv is not None:
                    v = max(v, vv)
                dp1[i][j] = v

    V.reverse()
    dp2 = [[None for i in range(gsize)] for i in range(gsize)]
    dp2[0][0] = 0
    for i, value in enumerate(V, 1):
        for j in range(gsize):
            if dp2[i - 1][j] is not None:
                dp2[i][j] = dp2[i - 1][j] + value

            v = dp2[i - 1][j - 1]
            if j >= 1 and dp2[i - 1][j - 1] is not None:
                vv = dp2[i][j]
                if vv is not None:
                    v = max(v, vv)
                dp2[i][j] = v

    mm = 0
    for i1 in range(gsize):
        for j1 in range(gsize):
            for i2 in range(gsize):
                for j2 in range(gsize):
                    if dp1[i1][j1] is None:
                        continue
                    if dp2[i2][j2] is None:
                        continue

                    kh = dp1[i1][j1]+dp2[i2][j2]
                    if i1 + i2 + j1 + j2 > K:
                        continue
                    if i1 + i2 > N:
                        continue
                    #print(kh)
                    if kh == 10:
                        print(i1, j1, j2, j2)
                        print(dp1[i1][j1], dp2[i2][j2])
                    mm = max(kh, mm)


    #for j in dp1:
    #    print(j)
    #for j in dp2:
    #    print(j)

    return mm


#####################################################ライブラリ集ここから

def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def koenai_saidai_x_index(sorted_list, n):
    l = 0
    r = len(sorted_list)
    if len(sorted_list) == 0:
        return False
    if sorted_list[0] > n:
        return False

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] == n:
            return x
        elif sorted_list[x] > n:
            r = x
        else:
            l = x
    return l


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        # print(sorted_list)
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2) ** 2) % mod
    if p % 2 == 1:
        return (n * power(n, p - 1)) % mod


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import heapq as hq

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

ans=0
for i in range(1,min(N,K)+1): #取り出す個数
    for j in range(i+1):
        A=[]
        hq.heapify(A) #左から取り出す個数
        for k in range(j):
            hq.heappush(A,V[k])
        for k in range(i-j):
            hq.heappush(A,V[n-k-1])
        p=min(i,K-i) #しまえる個数
        while p>0:
            if A[0]<0:
                hq.heappop(A)
                p-=1
            else:
                break
        ans=max(sum(A),ans)
print(ans)

Submission status: Runtime Error

Solution code:
# coding: utf-8
import copy
import numpy as np

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

lcs = [0]+np.cumsum(v)
rcs = [0]+np.cumsum(rev)
# print(lcs,rcs)

ans = -10**20
for l in range(n+1):
  for r in range(n+1-l):
    able = True
    d = k - ( l + r )
    if d < 0:
      able = False
      break
    m = lcs[l] + rcs[r]
    t = v[0:l] + rev[0:r]
    m = sum(t)
    # print(t,l,r,m)
    t.sort()
    # print(t)
    d = min(d,l+r)
    for i in range(d):
      if 0 > t[i]:
        m -= t[i]
      else:
        break
    # print(m)
    ans = max(ans,m)

print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
import heapq
n, k = map(int, input().split())
v = list(map(int, input().split()))

result = []
for i in range(k):
    for j in range(k-i):
        jue = []
        heapq.heapify(jue)
        for ii in range(i):
            heapq.heappush(jue, v[ii])
        for jj in range(j):
            heapq.heappush(jue, v[-jj-1])
        for le in range(min(k-i-j, len(jue))):
            heapq.heappop(jue)
        result.append(sum(jue))

print(max(result))

Submission status: Runtime Error

Solution code:
from collections import deque
import heapq
n, k = map(int, input().split())
v = list(map(int, input().split()))

result = []
for i in range(k):
    for j in range(k-i):
        jue = []
        heapq.heapify(jue)
        for ii in range(i):
            heapq.heappush(jue, v[ii])
        for jj in range(j):
            heapq.heappush(jue, v[-jj-1])
        for le in range(min(k-i-j, i+j)):
            heapq.heappop(jue)
        result.append(sum(jue))

print(max(result))

Submission status: Runtime Error

Solution code:
from collections import deque
import heapq
n, k = map(int, input().split())

v = deque(list(map(int, input().split())))
j = []
heapq.heapify(j)

def solve(hep, jue, c, end=k):
    if c==k:
        return sum(hep)
    result = [0]
    if len(jue)!=0:
        x, y = hep.copy(), jue.copy()
        heapq.heappush(x, y.pop())
        result.append(solve(x, y, c+1))

        x, y = hep.copy(), jue.copy()
        heapq.heappush(x, y.popleft())
        result.append(solve(x, y, c+1))


    if len(hep)!=0:
        x, y = hep.copy(), jue.copy()
        y.append(heapq.heappop(x))
        result.append(solve(x, y, c+1))

        x, y = hep.copy(), jue.copy()
        y.appendleft(heapq.heappop(x))
        result.append(solve(x, y, c+1))

    return max(result)


print(solve(j, v, 0))

Submission status: Runtime Error

Solution code:
from copy import deepcopy
from collections import deque
from functools import partial, lru_cache
from heapq import heappush, heappop

n, k = map(int, inputs[0].split())
V = deque(map(int, inputs[1].split()))
W = []

def dfs(root, option, function):
    nodes, stack = [], [root]
    ans = 0
    while stack:
        current_node = stack.pop()
        if current_node in nodes:
            continue
        ans = function(current_node, ans)
        for n in option(current_node):
            if n not in nodes:
                stack.append(n)
    return ans

def option(node, limit):
    i, j = node
    if i+j < limit:
        return ((i+1, j), (i, j+1))
    return tuple()

def function(node, ans, W, V, limit, memo):
    if node in memo:
        return max(ans, memo[node])
    i, j = node
    W_, V_ = map(deepcopy, (W, V))
    for _ in range(i):
        if V_:
            heappush(W_, V_.pop())
    for _ in range(j):
        if V_:
            heappush(W_, V_.popleft())
    score = sum(W_)
    for _ in range(min(limit-i-j, i+j)):
        if W_ and W_[0] < 0:
            score -= heappop(W_)
    memo[node] = score
    print(i, j, min(limit-i-j, i+j), memo[node])
    return max(ans, memo[node])

ans = dfs((0, 0), partial(option, limit=min(n, k)), partial(function, W=W, V=V, limit=k, memo={}))
print(ans)

Submission status: Runtime Error

Solution code:
from copy import deepcopy
from collections import deque
from functools import partial, lru_cache
from heapq import heappush, heappop

inputs = open(0).readlines()
n, k = map(int, inputs[0].split())
V = deque(map(int, inputs[1].split()))
W = []


def dfs(root, option, function):
    nodes, stack = [], [root]
    ans = 0
    while stack:
        current_node = stack.pop()
        if current_node in nodes:
            continue
        ans = function(current_node, ans)
        for n in option(current_node):
            if n not in nodes:
                stack.append(n)
    return ans

def option(node, k):
    i, j = node
    if i+j < k:
        return ((i+1, j), (i, j+1))
    return tuple()

def function(node, ans, W, V, k, memo):
    if node in memo:
        return max(ans, memo[node])

    i, j = node
    W_, V_ = get_W_V(i)
    for _ in range(j):
        if V_:
            heappush(W_, V_.popleft())
    score = sum(W_)
    for _ in range(min(k-i-j, i+j)):
        if W_ and W_[0] < 0:
            score -= heappop(W_)
    memo[node] = score
    return max(ans, memo[node])

ans = dfs((0, 0), partial(option, k=k), partial(function, W=W, V=V, k=k, memo={}))
print(ans)

Submission status: Runtime Error

Solution code:
N,K = map(int,(input().split()))
V = list(map(int,(input().split())))
left = [0]*(N+1)
right = [0]*(N+1)
ans = []

for i in range(1,N+1):
    left[i] = left[i-1] + V[i-1]

for i in range(1,N+1):
    right[i] = right[i-1] + V[N-i]

for i in range(K+1):
    nega = []

    l = i
    for count in range(l):
        if l > 0 and V[count] < 0:
            nega.append(V[count])

    for j in range(K+1-i):

        r = j
        for count in range(1,r+1):
            if r > 0 and V[N-count] < 0:
                nega.append(V[N-count])

        b = K-i-j
        now = left[i] + right[j]
        nega.sort()
        s = 0
        for k in range(min(b,len(nega))):
            s += nega[k]
        
        if nega:
            ans.append(now-s)
        else:
            ans.append(now)

print(max(ans))

Submission status: Runtime Error

Solution code:
N,K = map(int,(input().split()))
V = list(map(int,(input().split())))
left = [0]*(N+1)
right = [0]*(N+1)
ans = []

for i in range(1,N+1):
    left[i] = left[i-1] + V[i-1]

for i in range(1,N+1):
    right[i] = right[i-1] + V[N-i]

for i in range(K+1):
    nega = []

    l = i
    for count in range(l):
        if l > 0 and V[count] < 0:
            nega.append(V[count])

    for j in range(K+1-i):

        r = j
        for count in range(1,r+1):
            if r > 0 and V[N-count] < 0:
                nega.append(V[N-count])

        b = K-i-j
        now = left[i] + right[j]
        nega.sort()
        s = 0
        for k in range(min(b,len(nega))):
            s += nega[k]
 
        ans.append(now-s)

print(max(ans))

Submission status: Runtime Error

Solution code:
import heapq as pq
from collections import deque
from itertools import accumulate
N,K = map(int,input().split())
v = list(map(int,input().split()))
acc = [0]+list(accumulate(v,lambda x,y: x+y))
anss = -1
for k in range(K+1):
    for i in range(k+1):
        ans = 0
        ls = deque(v)
        heap = []
        j = k-i
        ans += acc[i]+acc[-1]-acc[-1-j]
        for q in range(i):
            if ls:
                pq.heappush(heap,ls.popleft())
            else:
                break
        for q in range(j):
            if ls:
                pq.heappush(heap,ls.pop())
            else:
                break
        for i in range(K-k):
            if heap:
                x = pq.heappop(heap)
                if x < 0:
                    ans -= x
                else:
                    break
        anss = max(ans,anss)
print(anss)

Submission status: Runtime Error

Solution code:
"""from collections import *
from itertools import *
from bisect import *
from heapq import *

import math
from fractions import gcd
import sys
#input = sys.stdin.readline


"""
import copy
from collections import *
from heapq import *
N,K=map(int,input().split())
VVV=list(map(int,input().split()))
value=0

VV=deque(VVV)
Llst=[[]]
V=copy.copy(VV)
for i in range(min(K,N)):
    Llst.append(copy.copy(Llst[-1]))
    a=V.popleft()
    Llst[-1].append(a)

Rlst=[[]]
V=copy.copy(VV)
for i in range(min(K,N)):
    Rlst.append(copy.copy(Rlst[-1]))
    a=V.pop()
    Rlst[-1].append(a)

#print(Llst,Rlst)
for l in range(K):
    for r in range(K-l):
        lst=Llst[l]+Rlst[r]
        lst.sort(reverse=True)
        for i in range(K-l-r):
            if lst:
                if lst[-1]<0:
                    lst.pop()
                else:
                    break
            else:
                break
        value=max(value,sum(lst))
print(value)

Submission status: Runtime Error

Solution code:
"""from collections import *
from itertools import *
from bisect import *
from heapq import *

import math
from fractions import gcd
import sys
#input = sys.stdin.readline


"""
#import copy
from collections import *
from heapq import *
N,K=map(int,input().split())
VVV=list(map(int,input().split()))
value=0

VV=deque(VVV)
Llst=[[]]
V=VV.copy()
for i in range(min(K,N)):
    Llst.append(Llst[-1].copy())
    a=V.popleft()
    Llst[-1].append(a)

Rlst=[[]]
V=VV.copy()
for i in range(min(K,N)):
    Rlst.append(Rlst[-1].copy())
    a=V.pop()
    Rlst[-1].append(a)

#print(Llst,Rlst)
for l in range(K):
    for r in range(K-l):
        lst=Llst[l]+Rlst[r]
        lst.sort(reverse=True)
        for i in range(K-l-r):
            if lst:
                if lst[-1]<0:
                    lst.pop()
                else:
                    break
            else:
                break
        value=max(value,sum(lst))
print(value)

Submission status: Runtime Error

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

L_pos = 0
L_neg = []
dpl = [0 for _ in  range(k)]
for i in range(k):
  vi =V[i]
  if vi <= 0:
    L_neg.append(vi)
    continue
  L_pos += vi
  L_neg.sort()
  for j in range(min( len(L_neg), k-i )):
    dpl[i+j] = max(dpl[i+j], L_pos - sum(L_neg[k:]))
    
R_pos = 0
R_neg = []
V= V[::-1]
dpr = [0 for _ in  range(k)]
for i in range(k):
  vi =V[i]
  if vi <= 0:
    R_neg.append(vi)
    continue
  R_pos += vi
  R_neg.sort()
  for j in range(min( len(R_neg), k-i )):
    dpl[i+j] = max(dpl[i+j], R_pos - sum(R_neg[k:]))
  
ans = 0
for i in range(k):
  ans = max(ans, dpl[i]+dpr[k-i])
print(ans)

Submission status: Runtime Error

Solution code:
import heapq
from collections import deque
from copy import copy
n,k = map(int,input().split())
d = deque(list(map(int,input().split())))
maxvalue = 0
for i in range(k):
    for j in range(k-i+1):
        jewel = []
        x = copy(d)
        for _ in range(i):
            jewel.append(x.popleft())
        for _ in range(j):
            jewel.append(x.pop())
        heapq.heapify(jewel)
        for _ in range(k-i-j):
            if jewel:
                a = heapq.heappop(jewel)
                if a >= 0:
                    jewel.append(a)
                    break
        maxvalue = max(maxvalue,sum(jewel))
print(maxvalue)

Submission status: Runtime Error

Solution code:
import heapq

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

ans = []
for i in range(min(N, K)+1):
  for j in range(i+1):
    #print(i-j, j)
    # i-j個左から、i個右から取る
    lst = V[:i-j] + V[2*N-j:]
    #print(lst)
    heapq.heapify(lst)
    for _ in range(K-i):
      if len(lst) == 0:
        break
      elif min(lst) >= 0:
        ans.append(sum(lst))
        break
      else:
        heapq.heappop(lst)
        ans.append(sum(lst))
        #print(ans)
print(max(ans))

Submission status: Runtime Error

Solution code:
import heapq

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

ans = []
for i in range(min(N, K)):
  for j in range(i+1):
    # i-j個左から、i個右から取る
    lst = V[:i-j] + V[N-j:]
    #print(lst)
    heapq.heapify(lst)
    for _ in range(K-i):
      if len(lst) == 0:
        break
      elif min(lst) >= 0:
        ans.append(sum(lst))
        break
      else:
        heapq.heappop(lst)
        ans.append(sum(lst))
        #print(ans)
print(max(ans))

Submission status: Runtime Error

Solution code:
import heapq

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

ans = []
for i in range(min(N, K)):
  for j in range(i+1):
    #print(i-j, j)
    # i-j個左から、i個右から取る
    lst = V[:i-j] + V[N-j:]
    #print(lst)
    heapq.heapify(lst)
    for _ in range(K-i):
      if len(lst) == 0:
        break
      elif heapq.heappop(lst) >= 0:
        break
      else:
        ans.append(sum(lst))
print(max(ans))

Submission status: Runtime Error

Solution code:
from collections import deque

n,k = map(int,input().split())
D =map(int,input().split())
ans = 0

for toridasukaisu in range(min(k,n)+1):#0~min(k,n)回取り出す
    for i in range(toridasukaisu+1):
        value = []#取り出したもののそれぞれの価値
        l = i#左からi回取り出し
        r = toridasukaisu - i#右から取り出す回数-i回取り出す
        for j in range(l):
            value.append(D[j])
        for j in range(r):
            value.append(D[-1-j])

        value.sort()
        suterukazu = 0
        suterukaisu = k - toridasukaisu
        for e in value:
            if suterukazu >= suterukaisu:
                break
            if e < 0:
                suterukazu += 1
            
        ans = max(sum(value[suterukazu:]),ans)
        
print(ans)

Submission status: Runtime Error

Solution code:
def main():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    L = [(0, [])]
    R = [(0, [])]

    mp = 0
    mn = []
    for k in range(K):
        if k == len(V):
            break
        v = V[k]
        if v >= 0:
            mp += v
        else:
            mn.append(v)
            mn.sort()
        L.append((mp, tuple(mn)))

    mp = 0
    mn = []
    for k in range(K):
        i = len(V) - k - 1
        if i < 0:
            break
        v = V[i]
        if v >= 0:
            mp += v
        else:
            mn.append(v)
            mn.sort()
        R.append((mp, tuple(mn)))

    mval = 0
    for l in range(K + 1):
        if l == len(L) + 1:
            break
        lp, ln = L[l]
        for r in range(K - l):
            if l + r == len(V) or r == len(R) + 1:
                break
            rp, rn = R[r]
            val = rp + lp
            n = K - l - r
            if len(ln) + len(rn) > n:
                t = list(ln) + list(rn)
                t.sort()
                val += sum(t[n:])
            mval = max(mval, val)
    print(mval)


main()

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
v = list(map(int, input().split()))
mini = min(n, k)
value = 0
for a in range(mini + 1):
  for b in range(mini - a + 1):
    c = k - a - b
    j = v[:a] + v[n-b:]
    j.sort(reverse=True)
    for _ in range(c):
      if j[-1] < 0:
        j.pop()
      else:
        break
    value = max(value, sum(j))
print(value)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque

input = sys.stdin.readline
n,k = map(int, input().split())

d = deque()
d.extend(map(int,input().split()))

q = deque()
total=[]
max = 0
for i in range(n):
    x = d.popleft()
    q.append(x)
    if max < x:
        max = x
        num_max = i
    d.append(x)
if num_max < n - num_max:
    if num_max <=k:
        for i in range(num_max):
            total.append(d.popleft())
    else:
        num_max = 0
else:
    if n - num_max <= k:
        for i in range(num_max):
            total.append(d.pop())
    else:
        num_max = 0



for i in range(k-num_max):
    left = d.popleft()
    right = d.pop()
    a = 0
    if right < left:
        d.append(right)
        for j in range(i+num_max):
            if left < total[j]*(-1):
                d.appendleft(left)
                left = total[j]*(-1)
                a = 1
        add = left
    else:
        d.appendleft(left)
        for j in range(i+num_max):
            if right < total[j]*(-1):
                d.append(right)
                right = total[j]*(-1)
                a = 1
        add =right

    if a == 1:
        total[total.index(add*(-1))] = 0
        add = 0

    total.append(add)

total2=[]
for i in range(k):
    left = q.popleft()
    right = q.pop()
    a = 0
    if right < left:
        q.append(right)
        for j in range(i):
            if left < total2[j]*(-1):
                q.appendleft(left)
                left = total2[j]*(-1)
                a = 1
        add = left
    else:
        q.appendleft(left)
        for j in range(i):
            if right < total2[j]*(-1):
                q.append(right)
                right = total2[j]*(-1)
                a = 1
        add =right

    if a == 1:
        total2[total2.index(add*(-1))] = 0
        add = 0

    total2.append(add)

if sum(total2)<sum(total):
    if sum(total)<0:
        print(0)
    else:
        print(sum(total))
else:
    if sum(total2)<0:
        print(0)
    else:
        print(sum(total2))

Submission status: Runtime Error

Solution code:
import sys
from collections import deque

input = sys.stdin.readline
n,k = map(int, input().split())

d = deque()
d.extend(map(int,input().split()))

q = deque()
total=[]
max = 0
for i in range(n):
    x = d.popleft()
    q.append(x)
    if max < x:
        max = x
        num_max = i
    d.append(x)
if num_max < n - num_max:
    if num_max <=k:
        for i in range(num_max):
            total.append(d.popleft())
    else:
        num_max = 0
else:
    if n - num_max <= k:
        for i in range(num_max):
            total.append(d.pop())
    else:
        num_max = 0



for i in range(k-num_max):
    left = d.popleft()
    right = d.pop()
    a = 0
    if right < left:
        d.append(right)
        for j in range(i+num_max):
            if left < total[j]*(-1):
                d.appendleft(left)
                left = total[j]*(-1)
                a = 1
        add = left
    else:
        d.appendleft(left)
        for j in range(i+num_max):
            if right < total[j]*(-1):
                d.append(right)
                right = total[j]*(-1)
                a = 1
        add =right

    if a == 1:
        total[total.index(add*(-1))] = 0
        add = 0

    total.append(add)

total2=[]
print(q)
for i in range(k):
    left = q.popleft()
    right = q.pop()
    a = 0
    if right < left:
        q.append(right)
        for j in range(i):
            if left < total2[j]*(-1):
                q.appendleft(left)
                left = total2[j]*(-1)
                a = 1
        add = left
    else:
        q.appendleft(left)
        for j in range(i):
            if right < total2[j]*(-1):
                q.append(right)
                right = total2[j]*(-1)
                a = 1
        add =right

    if a == 1:
        total2[total2.index(add*(-1))] = 0
        add = 0

    total2.append(add)

if sum(total2)<sum(total):
    if sum(total)<0:
        print(0)
    else:
        print(sum(total))
else:
    if sum(total2)<0:
        print(0)
    else:
        print(sum(total2))

Submission status: Runtime Error

Solution code:
import sys
from collections import deque

input = sys.stdin.readline
n,k = map(int, input().split())

d = deque()
d.extend(map(int,input().split()))

total=[]
e = d
max = 0
for i in range(n):
    x = e.popleft()
    if max < x:
        max = x
        num_max = i
    e.append(x)

if num_max < n - num_max:
    if num_max <=k:
        for i in range(num_max):
            total.append(d.popleft())
    else:
        num_max = 0
else:
    if n - num_max <= k:
        for i in range(num_max):
            total.append(d.pop())
    else:
        num_max = 0



for i in range(k-num_max):
    left = d.popleft()
    right = d.pop()
    a = 0
    if right < left:
        d.append(right)
        for j in range(i+num_max):
            if left < total[j]*(-1):
                d.appendleft(left)
                left = total[j]*(-1)
                a = 1
        add = left
    else:
        d.appendleft(left)
        for j in range(i+num_max):
            if right < total[j]*(-1):
                d.append(right)
                right = total[j]*(-1)
                a = 1
        add =right

    if a == 1:
        total[total.index(add*(-1))] = 0
        add = 0

    total.append(add)

if sum(total)<0:
    print(0)
else:
    print(sum(total))

Submission status: Runtime Error

Solution code:
import sys
from collections import deque

input = sys.stdin.readline
n,k = map(int, input().split())

d = deque()
d.extend(map(int,input().split()))

total=[]
e = d
max = 0
for i in range(n):
    x = e.popleft()
    if max < x:
        max = x
    e.append(x)
num_max=e.index(max)

if num_max < n - num_max:
    if num_max <=k:
        for i in range(num_max):
            total.append(d.popleft())
    else:
        num_max = 0
else:
    if n - num_max <= k:
        for i in range(num_max):
            total.append(d.pop())
    else:
        num_max = 0



for i in range(k-num_max):
    left = d.popleft()
    right = d.pop()
    a = 0
    if right < left:
        d.append(right)
        for j in range(i+num_max):
            if left < total[j]*(-1):
                d.appendleft(left)
                left = total[j]*(-1)
                a = 1
        add = left
    else:
        d.appendleft(left)
        for j in range(i+num_max):
            if right < total[j]*(-1):
                d.append(right)
                right = total[j]*(-1)
                a = 1
        add =right

    if a == 1:
        total[total.index(add*(-1))] = 0
        add = 0

    total.append(add)

if sum(total)<0:
    print(0)
else:
    print(sum(total))

Submission status: Runtime Error

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


def doit(vv, kk):
    if kk == 0:
        return 0
    return max(vv[0] + doit(vv[1:], kk - 1),
               vv[-1] + doit(vv[:-1], kk - 1),
               doit(vv[1:], kk - 2) if kk > 1 else 0,
               doit(vv[:-1], kk - 2) if kk > 1 else 0)


print(doit(vs, k))

Submission status: Runtime Error

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

ans=-10**9
for l in range(K+1):
    for r in range(max(1,K+1-l)):
        for d in range(max(1,K+1-l-r)):
            h=V[:l]
            heapq.heapify(h)
            for i in range(r): heapq.heappush(h, V[-1-i])
            for i in range(min(d,len(h))): heapq.heappop(h)
            ans=max(ans,sum(h))
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
import heapq

N, K=map(int, input().split())
V=list(map(int, input().split()))
lim=min(N, K)
ans=0
for num in range(lim+1):
    for A in range(num+1):
        B=num-A
        d=deque(V)
        hands=[]
        while d and len(h)<A:
            hands.append(d.popleft())
        while d and len(h)<A+B:
            hands.append(d.pop())
        heapq.heapify(hands)
        cnt=K-num
        while len(hands) and hands[0]<0 and cnt>0:
            cnt-=1
            heapq.heappop(hands)
        ans=max(ans, sum(hands))
print(ans)