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: Wrong Answer

Solution code:
import copy

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

result = 0
# i個取って，ret-1個戻す
for i in reversed(range(min(N,K)+1)):
    #print('i:',i)
    for sp in range(i+1): # 左右の分け方
        #print('right',sp)
        #print('left',i-sp)
        tmp = []
        V_tmp = copy.copy(V)
        #print('元々：',V_tmp)
        tmp.extend(V_tmp[:sp]) # 左端追加
        #print('left',V_tmp[:sp])
        tmp.extend(V_tmp[N-(i-sp):]) #右端追加
        #print('right',V_tmp[N-(i-sp):])
        value = sum(tmp)
        # ret個戻す
        for ret in range(0, min(K-i,i)): #残り操作回数か取った石の個数iの小さい方
            if ret < i:
                #print('ret',ret)
                if tmp[ret] < 0:
                    value -= tmp[ret]
                #print('手元の宝石：',tmp)
        result = max(result,value)
            #print()

print(result)

Submission status: Wrong Answer

Solution code:
import copy

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

result = 0
# i個取って，ret-1個戻す
for i in reversed(range(min(N,K)+1)):
    #print('i:',i)
    for sp in range(i+1): # 左右の分け方
        #print('right',sp)
        #print('left',i-sp)
        tmp = []
        V_tmp = copy.copy(V)
        #print('元々：',V_tmp)
        tmp.extend(V_tmp[:sp]) # 左端追加
        #print('left',V_tmp[:sp])
        tmp.extend(V_tmp[N-(i-sp):]) #右端追加
        #print('right',V_tmp[N-(i-sp):])
        value = sum(tmp)
        # ret個戻す
        for ret in range(min(K-i,i)): #残り操作回数か取った石の個数iの小さい方
            if ret < i:
                #print('ret',ret)
                if tmp[ret] < 0:
                    value -= tmp[ret]
                #print('手元の宝石：',tmp)
                result = max(result,value)
            #print()

print(result)

Submission status: Wrong Answer

Solution code:
import copy

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

result = 0
# i個取って，ret-1個戻す
for i in reversed(range(min(N,K)+1)):
    #print('i:',i)
    for sp in range(i+1): # 左右の分け方
        #print('right',sp)
        #print('left',i-sp)
        tmp = []
        V_tmp = copy.copy(V)
        #print('元々：',V_tmp)
        tmp.extend(V_tmp[:sp]) # 左端追加
        #print('left',V_tmp[:sp])
        tmp.extend(V_tmp[N-(i-sp):]) #右端追加
        #print('right',V_tmp[N-(i-sp):])
        value = sum(tmp)
        # ret個戻す
        for ret in range(min(K-i,i)): #残り操作回数か取った石の個数iの小さい方
            if ret < i:
                #print('ret',ret)
                if tmp[ret] < 0:
                    value -= tmp[ret]
                #print('手元の宝石：',tmp)
                result = max(result,value)
            #print()

print(value)

Submission status: Wrong Answer

Solution code:
import copy

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

value = 0
# i個取って，ret-1個戻す
for i in reversed(range(min(N,K)+1)):
    #print('i:',i)
    for sp in range(i+1): # 左右の分け方
        #print('right',sp)
        #print('left',i-sp)
        tmp = []
        V_tmp = copy.copy(V)
        #print('元々：',V_tmp)
        tmp.extend(V_tmp[:sp]) # 左端追加
        #print('left',V_tmp[:sp])
        tmp.extend(V_tmp[N-(i-sp):]) #右端追加
        #print('right',V_tmp[N-(i-sp):])
        if V_tmp == []:
            break
        # ret個戻す
        for ret in range(min(K-i,i)): #残り操作回数か取った石の個数iの小さい方
            if (ret < i):
                #print('ret',ret)
                tmp = list(filter(lambda x: x not in sorted(tmp)[:ret],tmp))
                #print('手元の宝石：',tmp)
                value = max(value,sum(tmp))
            #print()

print(value)

Submission status: Wrong Answer

Solution code:
import copy

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

value = 0
# i個取って，ret-1個戻す
for i in reversed(range(min(N,K)+1)):
    #print('i:',i)
    for ret in range(min(N,K)+1-i): #戻す個数はret個
        if (ret < i):
            #print('ret',ret)
            for sp in range(i+1): # 左右の分け方
                #print('right',sp)
                #print('left',i-sp)
                tmp = []
                V_tmp = copy.copy(V)
                #print('元々：',V_tmp)
                tmp.extend(V_tmp[:sp]) # 左端追加
                #print('left',V_tmp[:sp])
                tmp.extend(V_tmp[N-(i-sp):]) #右端追加
                #print('right',V_tmp[N-(i-sp):])
                if V_tmp == []:
                    break
                # ret個戻す
                tmp = list(filter(lambda x: x not in sorted(tmp)[:ret],tmp))
                #print('手元の宝石：',tmp)
                value = max(value,sum(tmp))
            #print()

print(value)

Submission status: Wrong Answer

Solution code:
import copy

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

value = 0

# i個取って，ret-1個戻す
for i in reversed(range(min(N,K)+1)):
    #print('i:',i)
    for ret in range(min(N,K)+1-i): #戻す個数はret個
        if (ret < i):
            #print('ret',ret)
            for sp in range(i): # 左右の分け方
                #print('right',sp)
                #print('left',i-sp)
                tmp = []
                V_tmp = copy.copy(V)
                #print('元々：',V_tmp)
                tmp.extend(V_tmp[:sp]) # 左端追加
                tmp.extend(V_tmp[N-(i-sp):]) #右端追加
                # ret個戻す
                tmp = list(filter(lambda x: x not in sorted(tmp)[:ret],tmp))
                #print('手元の宝石：',tmp)
                value = max(value,sum(tmp))
            #print()

print(value)

Submission status: Wrong Answer

Solution code:
import copy

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

value = 0
# k+1個取って，ret-1個戻す
num = min(N,K)
for k in reversed(range(num)):
    for ret in range(num-k): #戻す個数はret個
        if (ret < k+1):
            #print('{}個取って{}戻す'.format(k+1,ret))
            for i in range(k+1+1): # 左右の分け方
                tmp = []
                V_tmp = copy.copy(V)
                #print('元々：',V_tmp)
                tmp.extend(V_tmp[:i]) # 左端
                #print('左端：',V_tmp[:i])
                V_tmp = V_tmp[i:]
                #print('左端取った：',V_tmp)
                if (k+1-i) > 0:
                    tmp.extend(V_tmp[-(k+1-i):]) #右端
                    #print('右端：',V_tmp[-(k+1-i):])
                # V_tmp = V_tmp[:-(k+1-i)]
                # print('右端取った：',V_tmp)
                if V_tmp == []:
                    break
                tmp = list(filter(lambda x: x not in sorted(tmp)[:ret],tmp))
                #print('手元の宝石：',tmp)
                value = max(value,sum(tmp))
            #print()

print(value)

Submission status: Wrong Answer

Solution code:
import copy

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

value = 0
# k+1個取って，ret-1個戻す
for k in reversed(range(K)):
    for ret in range(K-k): #戻す個数はret個
        if (ret < k+1):
            print('{}個取って{}戻す'.format(k+1,ret))
            for i in range(k+1+1): # 左右の分け方
                tmp = []
                V_tmp = copy.copy(V)
                #print('元々：',V_tmp)
                tmp.extend(V_tmp[:i]) # 左端
                #print('左端：',V_tmp[:i])
                V_tmp = V_tmp[i:]
                #print('左端取った：',V_tmp)
                if (k+1-i) > 0:
                    tmp.extend(V_tmp[-(k+1-i):]) #右端
                    #print('右端：',V_tmp[-(k+1-i):])
                # V_tmp = V_tmp[:-(k+1-i)]
                # print('右端取った：',V_tmp)
                if V_tmp == []:
                    break
                tmp = list(filter(lambda x: x not in sorted(tmp)[:ret],tmp))
                print('手元の宝石：',tmp)
                value = max(value,sum(tmp))
            #print()

print(value)

Submission status: Wrong Answer

Solution code:
import copy

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

value = 0
# k+1個取って，ret-1個戻す
for k in reversed(range(K)):
    for ret in range(K-k): #戻す個数はret個
        if (ret < k+1):
            for i in range(k+1+1): # 左右の分け方
                tmp = []
                V_tmp = copy.copy(V)
                tmp.extend(V_tmp[:i]) # 左端
                V_tmp = V_tmp[i:]
                tmp.extend(V_tmp[-(k+1-i):]) #右端
                V_tmp = V_tmp[:-(k+1-i)]
                if V_tmp == []:
                    break
                tmp = list(filter(lambda x: x not in sorted(tmp)[:ret],tmp))
                print(tmp)
                value = max(value,sum(tmp))

print(value)

Submission status: Wrong Answer

Solution code:
import copy

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

value = 0
# k+1個取って，ret-1個戻す
for k in reversed(range(K)):
    for ret in range(K-k): #戻す個数はret個
        if (ret < k+1):
            for i in range(k+1+1): # 左右の分け方
                tmp = []
                V_tmp = copy.copy(V)
                for sp in range(i):
                    tmp.extend(V_tmp[:i]) # 左端
                    V_tmp = V_tmp[i:]
                    tmp.extend(V_tmp[-(k-i):]) #右端
                    V_tmp = V_tmp[:-(k-i)]
                    if V_tmp == []:
                        break
                print(tmp)
                tmp = list(filter(lambda x: x not in sorted(tmp)[:ret],tmp))
                value = max(value,sum(tmp))

print(value)

Submission status: Wrong Answer

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

max_ = 0
for a in range(K + 1):
    for b in range(K - a + 1):
        if a + b > N:
            continue

        jwl = V[:a]
        jwl += V[N - b:]
        rmv = K - (a + b)
        jwl.sort()

        max_ = max(max_, sum(jwl[rmv:]))


print(max_)

Submission status: Wrong Answer

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

max_ = 0
for a in range(K + 1):

    for b in range(K - a + 1):
        jwl = V[:a]
        jwl += V[N - b:]
        rmv = K - (a + b)
        jwl.sort()

        max_ = max(max_, sum(jwl[rmv:]))


print(max_)

Submission status: Wrong Answer

Solution code:
def main():
    n,k = map(int,input().split())
    v = list(map(int,input().split()))
    m = 0
    for k_ in range(k+1):
        v_c = v
        if k_>n:
            v_ = v_c
            v_c = []
            s = k-n
        else:
            v_ = v_c[0:k_]
            v_c = v_c[k_:]
            s = k-k_
        for i in range(s):
            if i>len(v_c):
                v__ =v_+ v_c
                s_ = s-len(v_c)
            else:
                v__ = v_+ v_c[len(v_c)-i:]
                s_ = s-i
            while s_>0 and len(v__)>0 and min(v__)<0:
                v__.pop(v__.index(min(v__)))
                s_ = s_-1
            if sum(v__)>m:
                m = sum(v__)
    print(m)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import heapq
n, k = map(int, input().split())
r = min(n, k)
v = list(map(int, input().split()))
ans = 0
for i in range(1, r+1):
  for j in range(i+1):
    a = j
    b = i-j
    v_temp = v[:a]
    v_temp.extend(v[n-b:])
    heapq.heapify(v_temp)
    for k in range(r-i):
      get = heapq.heappop(v_temp)
      if get>=0:
        heapq.heappush(v_temp, get)
        break
      if not v_temp:
        break
    v_temp.append(0)
    ans = max(ans, sum(v_temp))
print(ans)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
if N<=K:
  W=sorted(V)
  h=sum(V)
  for i in range(K-N):
    if W[i]<0:
      h-=W[i]
    else:
      break
else:
  ans=[]
  for i in range(K):
    for j in range(i+1):
      l=V[0:i-j]+V[N-j:N]
      l.sort()
      H=sum(l)
      for k in range(min(i,K-i)):
        if l[k]<0:
          H-=l[k]
        else:
          break
      ans.append(H)
  h=max(ans)
print(h)

Submission status: Wrong Answer

Solution code:
from collections import deque
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import permutations,combinations
from collections import defaultdict,Counter
from bisect import bisect_left,bisect_right
# from math import gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint

def myinput():
    return map(int,input().split())

def mylistinput(n):
    return [ list(myinput()) for _ in range(n) ]

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse_flag):
    data.sort(key=lambda x:x[col],reverse=reverse_flag)
    return data

def mymax(data):
    M = -1*float("inf")
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float("inf")
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(" ")
        elif type(ls[0])==str:
            print(" ".join(ls))
        elif type(ls[0])==int:
            print(" ".join(map(str,ls)))
        else:
            print("Output Error")
    else:
        if len(ls)==0:
            print("")
        elif type(ls[0])==str:
            print("".join(ls))
        elif type(ls[0])==int:
            print("".join(map(str,ls)))
        else:
            print("Output Error")

# ----- heapq ここから-----
import heapq
class Reverse:
    def __init__(self, val):
        self.val = val
        
    def __lt__(self, other):
        return self.val > other.val
        
    def __repr__(self):
        return repr(self.val)
    
class Heapq:
    def __init__(self, arr, desc = False):
        if desc:
            for i in range(len(arr)):
                arr[i] = Reverse(arr[i])
        self.desc = desc
        self.hq = arr
        heapq.heapify(self.hq)
 
    def pop(self):
        if self.desc: return heapq.heappop(self.hq).val
        else: return heapq.heappop(self.hq)
 
    def push(self, a):
        if self.desc: heapq.heappush(self.hq, Reverse(a))
        else: heapq.heappush(self.hq, a)
 
    def top(self):
        if self.desc: self.hq[0].val
        else: return self.hq[0]
# ----- heapq ここまで-----

n,k = myinput()
v = list(myinput())
vr = v[::-1]

ls = [-1,-1]
ans = -float("inf")
for a in range(k+1):
    for b in range(n-a+1):
        have = []
        have.extend( v[:a] )
        have.extend( vr[:b] )
        p = [ i for i in have if i>=0 ]
        m = [ i for i in have if i<0 ]
        m.sort()
        r = k - a - b
        m = m[r:]
        ans_tmp = sum(p)+sum(m)
        if ans<ans_tmp:
            ls[0] = a
            ls[1] = b
        ans = max(ans,ans_tmp)
# print(ls)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import permutations,combinations
from collections import defaultdict,Counter
from bisect import bisect_left,bisect_right
# from math import gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint

def myinput():
    return map(int,input().split())

def mylistinput(n):
    return [ list(myinput()) for _ in range(n) ]

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse_flag):
    data.sort(key=lambda x:x[col],reverse=reverse_flag)
    return data

def mymax(data):
    M = -1*float("inf")
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float("inf")
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(" ")
        elif type(ls[0])==str:
            print(" ".join(ls))
        elif type(ls[0])==int:
            print(" ".join(map(str,ls)))
        else:
            print("Output Error")
    else:
        if len(ls)==0:
            print("")
        elif type(ls[0])==str:
            print("".join(ls))
        elif type(ls[0])==int:
            print("".join(map(str,ls)))
        else:
            print("Output Error")

# ----- heapq ここから-----
import heapq
class Reverse:
    def __init__(self, val):
        self.val = val
        
    def __lt__(self, other):
        return self.val > other.val
        
    def __repr__(self):
        return repr(self.val)
    
class Heapq:
    def __init__(self, arr, desc = False):
        if desc:
            for i in range(len(arr)):
                arr[i] = Reverse(arr[i])
        self.desc = desc
        self.hq = arr
        heapq.heapify(self.hq)
 
    def pop(self):
        if self.desc: return heapq.heappop(self.hq).val
        else: return heapq.heappop(self.hq)
 
    def push(self, a):
        if self.desc: heapq.heappush(self.hq, Reverse(a))
        else: heapq.heappush(self.hq, a)
 
    def top(self):
        if self.desc: self.hq[0].val
        else: return self.hq[0]
# ----- heapq ここまで-----

n,k = myinput()
v = list(myinput())
vr = v[::-1]

ans = -float("inf")
for a in range(k+1):
    for b in range(k-a+1):
        have = []
        have.extend( v[:a] )
        have.extend( vr[:b] )
        p = [ i for i in have if i>=0 ]
        m = [ i for i in have if i<0 ]
        m.sort()
        r = k - a - b
        if len(m)!=0:
            m = m[r:]
        else:
            m = []
        ans_tmp = sum(p)+sum(m)
        ans = max(ans,ans_tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import permutations,combinations
from collections import defaultdict,Counter
from bisect import bisect_left,bisect_right
# from math import gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint

def myinput():
    return map(int,input().split())

def mylistinput(n):
    return [ list(myinput()) for _ in range(n) ]

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse_flag):
    data.sort(key=lambda x:x[col],reverse=reverse_flag)
    return data

def mymax(data):
    M = -1*float("inf")
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float("inf")
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(" ")
        elif type(ls[0])==str:
            print(" ".join(ls))
        elif type(ls[0])==int:
            print(" ".join(map(str,ls)))
        else:
            print("Output Error")
    else:
        if len(ls)==0:
            print("")
        elif type(ls[0])==str:
            print("".join(ls))
        elif type(ls[0])==int:
            print("".join(map(str,ls)))
        else:
            print("Output Error")

# ----- heapq ここから-----
import heapq
class Reverse:
    def __init__(self, val):
        self.val = val
        
    def __lt__(self, other):
        return self.val > other.val
        
    def __repr__(self):
        return repr(self.val)
    
class Heapq:
    def __init__(self, arr, desc = False):
        if desc:
            for i in range(len(arr)):
                arr[i] = Reverse(arr[i])
        self.desc = desc
        self.hq = arr
        heapq.heapify(self.hq)
 
    def pop(self):
        if self.desc: return heapq.heappop(self.hq).val
        else: return heapq.heappop(self.hq)
 
    def push(self, a):
        if self.desc: heapq.heappush(self.hq, Reverse(a))
        else: heapq.heappush(self.hq, a)
 
    def top(self):
        if self.desc: self.hq[0].val
        else: return self.hq[0]
# ----- heapq ここまで-----

n,k = myinput()
v = list(myinput())
vr = v[::-1]

ans = -float("inf")
for a in range(k+1):
    for b in range(k-a+1):
        have = []
        have.extend( v[:a] )
        have.extend( vr[:b] )
        p = [ i for i in have if i>=0 ]
        m = [ i for i in have if i<0 ]
        m.sort()
        r = k - a - b     
        m = m[r:]
        ans_tmp = sum(p)+sum(m)
        ans = max(ans,ans_tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
import sys,queue,math,copy,itertools,bisect,collections
INF = 10**9
LI = lambda : [int(x) for x in sys.stdin.readline().split()]
_LI = lambda : [int(x)-1 for x in sys.stdin.readline().split()]
NI = lambda : int(sys.stdin.readline())
N,K = LI()
dq = LI()

ans = -INF
for r in range(N+1):
    if K < N - r: continue

    ret = 0
    if r:
        for i in range(N-r+1):
            q = dq[:i] + dq[i+r:]
            ret = sum(q)
            q.sort()
            for j in range(K - (N-r)):
                if j >= len(q)-1 : break
                if q[j] < 0:
                    ret -= q[j]
                else:
                    break
            ans = max(ans,ret)
print(ans)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
ans=0
for a in range(min(N,K)+1):
    for b in range(min(N,K)+1-a):
        v=[]
        value=sum(V[:a])
        v.extend(V[:a])
        if b!=0:
            value=value+sum(V[-b:])
            v.extend(V[-b:])
        v.sort()
        for i in range(min(a+b,min(N,K)-a-b)):
            if v[i]<0:
                value=value-v[i]
            else:
                break
        ans=max(ans,value)
print(ans)

Submission status: Wrong Answer

Solution code:
# D - equeue

import heapq

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

ans = 0
for l in range(k+1):
    for r in range(k-l):
        if l+r>n:
            continue
        tmp = 0
        s = []
        for i in range(l):
            tmp += v[i]
            heapq.heappush(s, v[i])

        for i in range(n-r, n):
            tmp += v[i]
            heapq.heappush(s, v[i])
            
        for i in range(k-l-r):
            if len(s)==0:
                break
            if s[0]>0:
                break
            tmp -= heapq.heappop(s)
        
        ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
# D - equeue

import heapq

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

ans = 0
for l in range(k+1):
    for r in range(k-l):
        if l+r>n:
            continue
        tmp = 0
        s = []
        for i in range(l):
            tmp += v[i]
            heapq.heappush(s, v[i])

        for i in range(n-r, n):
            tmp += v[i]
            heapq.heappush(s, v[i])
            
        for i in range(k-l-r):
            if i>=len(s):
                break
            if s[0]>0:
                break
            tmp -= heapq.heappop(s)
        
        ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

Solution code:

N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for i in range(K):
  for j in range(N, max(N-1-(K-i), i-1), -1):
    bag = []
    bag += V[:i] + V[j:]
    bag.sort()
    idx = 0
    if len(bag) == 0:
      continue
    if len(bag) == 1:
      ans = max(ans, sum(bag))
      continue
    if len(bag) == K:
      ans = max(ans, sum(bag))
      continue
    tmp = 0
    for k in range(min(K-len(bag), len(bag))):
      if bag[k] < 0:
        tmp -= bag[k]
    #print(sum(bag), tmp, sum(bag)+tmp)
    ans = max(ans, sum(bag)+tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for i in range(K):
  for j in range(N, max(N-1-(K-i), i), -1):
    bag = []
    bag += V[:i] + V[j:]
    bag.sort()
    idx = 0
    if len(bag) == 0:
      continue
    if len(bag) == 1:
      ans = max(ans, sum(bag))
      continue
    if len(bag) == K:
      ans = max(ans, sum(bag))
      continue
    tmp = 0
    for k in range(min(K-len(bag), len(bag))):
      if bag[k] < 0:
        tmp -= bag[k]
    #print(sum(bag), tmp, sum(bag)+tmp)
    ans = max(ans, sum(bag)+tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for i in range(K):
  for j in range(N, N-1-(K-i), -1):
    bag = []
    bag += V[:i] + V[j:]
    bag.sort()
    idx = 0
    if len(bag) == 0:
      continue
    if len(bag) == 1:
      ans = max(ans, sum(bag))
      continue
    if len(bag) == K:
      ans = max(ans, sum(bag))
      continue
    tmp = 0
    for k in range(min(K-len(bag), len(bag))):
      if bag[k] < 0:
        tmp -= bag[k]
    ans = max(ans, sum(bag)+tmp)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for i in range(K):
  for j in range(N, N-1-(K-i), -1):
    bag = []
    bag += V[:i] + V[j:]
    bag.sort()
    idx = 0
    if len(bag) == 0:
      continue
    if len(bag) == K:
      continue
    for k in range(min(K-len(bag), len(bag))):
      if bag[k] < 0:
        idx = k

    ans = max(ans, sum(bag[idx+1:]))
print(ans)

Submission status: Wrong Answer

Solution code:
import time
startTimeProblem=time.time()

import fileinput, sys, itertools, functools
from math import *
from bisect import *
from heapq import *
from collections import *

def lcm(a, b):  
    return (a*b)/gcd(a, b)

class InputHelper:
    def __init__(self):
        self.myinput = fileinput.input()

    def isLocal(self):
        return not fileinput.isstdin()

    def int(self):
        return int(self.myinput.readline().rstrip())

    def ints(self):
        return [int(_) for _ in self.myinput.readline().rstrip().split()]

    def str(self):
        return self.myinput.readline().rstrip()

    def strs(self):
        return [_ for _ in self.myinput.readline().rstrip().split()]

class OutputHelper:
    def int(self, a):
        print(a)    

    def ints(self, a):  
        print(" ".join([str(_) for _ in a]))
    
    def intsNL(self, a):
        for _ in a:
            print(_)
    
    def str(self, s):
        print(s)

    def strs(self, s):
        print(" ".join([_ for _ in s]))

    def strsNL(self, s):
        for st in s:
            print(st)

class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None
        self.prev = None

In = InputHelper()
Out = OutputHelper()

######################################

N, K = In.ints()
V = In.ints()

class Solution():
    def __init__(self, K, V):
        self.ans = 0
        self.k = K
        self.posSum = 0
        self.negPreSum = [0]
        self.V = V

    def rec(self, fromIncl, toIncl):
        self.k -= 1
        canCallNext = self.k>0 and fromIncl!=toIncl

        #taketh left part
        leftVal = self.V[fromIncl]
        if leftVal>=0:
            self.posSum+=leftVal
        else:
            self.negPreSum.append(self.negPreSum[-1]+leftVal)

        negIdx = max(0, len(self.negPreSum)-1-self.k)
        self.ans = max(self.ans, self.posSum+self.negPreSum[negIdx])

        if canCallNext:
            self.rec(fromIncl+1, toIncl)
        
        if leftVal>=0:
            self.posSum-=leftVal
        else:
            self.negPreSum.pop(-1)
        
        #taketh right
        rightVal = self.V[toIncl]
        if rightVal>=0:
            self.posSum+=rightVal
        else:
            self.negPreSum.append(self.negPreSum[-1]+rightVal)

        negIdx = max(0, len(self.negPreSum)-1-self.k)
        self.ans = max(self.ans, self.posSum+self.negPreSum[negIdx])

        if canCallNext:
            self.rec(fromIncl, toIncl-1)

        if rightVal>=0:
            self.posSum-=rightVal
        else:
            self.negPreSum.pop(-1)

        self.k += 1


sol = Solution(K, V)
sol.rec(0, N-1)
Out.int(sol.ans)

######################################

if len(sys.argv)>2 and sys.argv[2]=="TIMEIT":
    fin = (time.time()-startTimeProblem)*1000
    print("{:.2f}".format(fin) + "ms")