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.

Solution (Python):
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,k = inpl()
a = inpl()
res = 0
for ope in range(k+1):
    for pick in range(ope+1):
        if pick > n: continue
        back = ope - pick
        for lp in range(pick+1):
            rp = pick - lp
            
            q = []
            for i in range(lp):
                q.append(a[i])
            for i in range(rp):
                q.append(a[-i-1])
            q.sort()
            ans = sum(q)
            res = max(res,ans)
            for i in range(back):
                if i >= pick: break
                ans -= q[i]
                res = max(res,ans)
print(res)

Solution (Python):
from bisect import bisect_left
N,K = map(int,input().split())
V = list(map(int,input().split()))
vmax = -10**9
for n in range(min(N,K)+1):
    A = V[:n]
    for m in range(min(N,K)-n+1):
        B = V[N-m:]
        B = B+A
        B = sorted(B)
        ind = bisect_left(B,0)
        k = min(ind,K-n-m)
        v = sum(B[k:])
        vmax = max(vmax,v)
print(vmax)

Solution (Python):
n, k, *a = map(int, open(0).read().split())

ans = 0
for l in range(0, k + 1):
    for r in range(0, k + 1 - l):
        if l == r == 0 or l + r > n:
            continue
        b = sorted(a[:l] + a[n - r:])
        c = min(k - l - r, len(b) - 1)
        ans = max(ans, sum(b[c:] if b[c] < 0 else filter(lambda x: x > 0, b)))
print(ans)

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

ans = 0
for l in range(0, k + 1):
    for r in range(0, k + 1 - l):
        if l == r == 0 or l + r > n:
            continue
        a = sorted(v[:l] + v[n - r:])
        m = min(k - l - r, len(a) - 1)
        ans = max(ans, sum(a[m:] if a[m] <
                           0 else filter(lambda x: x > 0, a)))
print(ans)

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

ans = 0

for l in range(n):
    for r in range(n+1)[::-1]:
        if l <= r and 0 <= (l+n-r) <= k: 
            q = v[:l] + v[r:n]
            q.sort(reverse = True)
            
            for i in range(k-(l+n-r)):
                if q == []:
                    break
                if q[-1] < 0:
                    q.pop()
                else:
                    break

            ans = max(ans, sum(q))
        else:
            continue

print(ans)

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

ans = 0

for l in range(n):
    for r in range(n+1)[::-1]:
        if l <= r and 0 <= (l+n-r) <= k: 
            q = v[:l] + v[r:n]
            q.sort(reverse = True)
            
            for i in range(k-(l+n-r)):
                if q == []:
                    break
                if q[-1] < 0:
                    q.pop()
                else:
                    break

            ans = max(ans, sum(q))
        else:
            continue

print(ans)

Solution (Python):
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  

N,K = MI()
V = LI()

ans = 0
for i in range(K+1):  
    for j in range(N+1):  
        for k in range(N+1):  
            if j + k > min(N,i):
                break
            l = i-j-k  
            if l > j+k:
                continue
            A = [V[m] for m in range(j)] + [V[N-1-m] for m in range(k)]
            A.sort(reverse=True)
            ans = max(ans,sum(A[m] for m in range(j+k-l)))
print(ans)

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

ans = 0
for left in range(n + 1):
    for right in range(n + 1):
        if left == 0 and right == 0:
            continue
        rest = k - left - right
        if left + right > n or rest < 0:
            break
        arr = v[:left] + v[n - right:]
        minus = 0
        neg = [x for x in arr if x < 0]
        if len(neg) > 0:
            neg.sort()
            minus = sum(neg[:rest])
        ans = max(ans, sum(arr) - minus)

print(ans)

Solution (Python):
import sys

N, K = map(int, sys.stdin.readline().split())
V = list(map(int, sys.stdin.readline().split()))

ans = 0

for i in range(N+1):
    if K < i:
        continue
    score = sum(V[0:i])
    
    ans = max(ans, score)
    for j in range(N+1):
        if N < i + j or K < i + j:
            continue
        tmp = score
        tmp += sum(V[N-j:])
        ans = max(ans, tmp)
        

        
        k = K - i - j
        if k < 0:
            continue
        negs = []
        for n in range(0, i):
            if V[n] < 0:
                negs.append(V[n])
        for n in range(N-j, N):
            if V[n] < 0:
                negs.append(V[n])
        negs.sort()
        
        tmp -= sum(negs[:k])
        ans = max(ans, tmp)
        

print(ans)

Solution (Python):
from bisect import bisect_left
N,K = map(int,input().split())
V = list(map(int,input().split()))
vmax = -10**9
for n in range(min(N,K)+1):
    A = V[:n]
    for m in range(min(N,K)-n+1):
        B = V[N-m:]
        B = sorted(A+B)
        ind = bisect_left(B,0)
        k = min(K-m-n,ind)
        cnt = sum(B[k:])
        vmax = max(vmax,cnt)
print(vmax)

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


ans = 0
for l in range(0, k + 1):
    for r in range(0, k + 1 - l):
        if l + r > n:
            continue
        suteru = k - l - r
        get = []
        for i in range(l):
            get.append(v[i])
        for i in range(n - 1, n - 1 - r, -1):
            get.append(v[i])
        get.sort()
        minus = 0
        while minus < min(suteru, len(get)) and get[minus] < 0:
            minus += 1
        ans = max(ans, sum(get[minus:]))
print(ans)

Solution (Python):
import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  
def LS2(): return list(sys.stdin.readline().rstrip())  

N,K = MI()
V = LI()

ans = 0
for i in range(K+1):  
    for j in range(N+1):  
        for k in range(N+1):  
            if j + k > min(N,i):
                break
            l = i-j-k
            if l > j+k:
                continue
            A = [V[m] for m in range(j)] + [V[N-1-m] for m in range(k)]
            A.sort(reverse=True)
            ans = max(ans,sum(A[m] for m in range(j+k-l)))
print(ans)

Solution (Python):
n,k=map(int,input().split())
v=list(map(int,input().split()))
finans=0
for l in range(n+1):
  for r in range(n-l+1):
    if l+r>k:
      continue
    ans=[]
    for i in range(l):
      ans.append(v[i])
    for i in range(n-1,n-r-1,-1):
      ans.append(v[i])
    ans.sort()
    i=-1
    for i in range(min(len(ans),k-(r+l))):
      if ans[i]>0:
        i-=1
        break
    ans1=0
    for j in range(i+1,len(ans)):
      ans1+=ans[j]
    finans=max(finans,ans1)
print(finans)

Solution (Python):
import copy
from collections import deque
N,K = map(int,input().split())
A = list(map(int,input().split()))
ans = 0
for k in range(K+1): 
  for left in range(N+1): 
    for right in range(N-left+1):
      push = k - (left + right)
      if push < 0 or push > left+right:
        continue
      Acopy = copy.copy(A)
      Acopy = deque(Acopy)
      B = []
      for t in range(left):
        temp = Acopy.popleft()
        B.append(temp)
      for t in range(right):
        
        temp = Acopy.pop()
        B.append(temp)
      B.sort()
      wa = sum(B)-sum(B[:push])
      ans = max(ans,wa)
print(ans)

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

ans = 0
for l in range(N+1):
    for r in range(N+1):
        if l+r > N or l+r > K: break
        arr = V[:l]
        if r: arr += V[-r:]
        arr.sort()
        rem = K - l - r
        tmp = 0
        for a in arr:
            if a < 0 and rem:
                rem -= 1
            else:
                tmp += a
        ans = max(ans, tmp)
print(ans)

Solution (Python):
n,k = map(int, input().split())
vl = list(map(int, input().split()))    

ans = 0
ab_max = min(n,k)
for l in range(ab_max+1):
    for r in range(ab_max+1):
        if l+r > k: continue
        if l > n-r: continue
        ls = vl[:l]
        rs = vl[n-r:]
        
        vals = ls + rs
        rem = k-(l+r)
        
        vals.sort()
        curr_sum = sum(vals)
        for i in range(rem):
            if i >= len(vals): break
            if vals[i] < 0: curr_sum -= vals[i]
            else: break
        
        ans = max(ans,curr_sum)

print(ans)

Solution (Python):
import random

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

if K==0:
    print(0)
    exit()

if 0:
    V=[random.randint(-10**7,10**7) for i in range(N)]

ans=-float("inf")

for i in range(N+1):
    for j in range(N-i+1):
        if i+j>K:
            continue
        tmp=[V[k] for k in range(i)]
        for k in range(j):
            tmp.append(V[-1-k])
        tmp.sort()
        rest=K-i-j
        minus=0
        base=sum(tmp)
        for k in range(min(rest,len(tmp))):
            if tmp[k]<0:
                minus+=tmp[k]
            else:
                break
        test=base-minus
        ans=max(ans,test)

print(ans)

Solution (Python):
from itertools import*
n,k=map(int,input().split())
v=list(map(int,input().split()))
ans=0
for i in range(k+1):
  if i>n:break
  for j in range(i+1):
    c=0
    d=sorted(v[:j]+v[n-i+j:])
    l=k-len(d)
    for m in d:
      if m<0 and l:
        l-=1
        continue
      c+=m
    ans=max(ans,c)
print(ans)

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

ans = 0
for l in range(min(n, k) + 1):
    for r in range(min(n, k) - l + 1):
        bag = sorted(v[:l] + v[n - r:])
        minus = sum(vi for vi in bag[:k - l - r] if vi < 0)
        ans = max(ans, sum(bag) - minus)
print(ans)

Solution (Python):
from itertools import accumulate

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

ans = 0
for l in range(min(n, k) + 1):
    for r in range(min(n, k) - l + 1):
        bag = sorted(v[:l] + v[n - r:])
        minus = sum(vi for vi in bag[:k - l - r] if vi < 0)
        ans = max(ans, sum(bag) - minus)
print(ans)

Solution (Python):
from itertools import accumulate

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

ans = 0
acc = [0] + list(accumulate(v))
for l in range(min(n, k) + 1):
    for r in range(min(n, k) - l + 1):
        minus = sorted(v[:l] + v[n - r:])
        bag = acc[l] - acc[0] + acc[n] - acc[n - r]
        bag -= sum(vi for vi in minus[:k - l - r] if vi < 0)
        ans = max(ans, bag)
print(ans)

Solution (Python):
import bisect, copy, heapq, math, sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
def celi(a,b):
    return -(-a//b)
sys.setrecursionlimit(5000000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

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

ans=0
for i in range(k+1):
    toru=i
    ireru=k-i
    
    for j in range(toru+1):
        l,r=j,n-(toru-j)
        if l>r:
            lst=v[:]
        else:
            lst=v[:l]+v[r:]
        
        lst.sort(reverse=True)
        for l in range(ireru):
            if lst and lst[-1]<0:
                lst.pop()
        ans=max(ans,sum(lst))

print(ans)

Solution (Python):
from itertools import accumulate

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

ans = 0
acc = [0] + list(accumulate(v))
for l in range(min(n, k) + 1):
    for r in range(min(n, k) - l + 1):
        minus = sorted(v[:l] + v[n - r:])
        bag = acc[l] - acc[0] + acc[n] - acc[n - r]
        bag -= sum(vi for vi in minus[:k - l - r] if vi < 0)
        ans = max(ans, bag)
print(ans)

Solution (Python):

"""
まず貪欲的なアルゴリズムを組めるか考えてみる。
所持している宝石のうち、価値が負であるものはできるだけ、筒に入れたい。できれば価値の低い順に。
所持している宝石のうち、価値が0以上であるものは、筒に入れる意味がない。
筒にある宝石のうち、価値が正のものはできるだけ取り出したい。できれば価値の高い順に。

ここまで考えると、宝石を筒に入れる作業は最後にやればよいことがわかる。
むしろ最後に寄せないと、筒の中に残っている価値の高い宝石を取り出すときに、入れた宝石が邪魔になる。
また、最後に行うため、左から入れるか右から入れるかは関係ない。
あと入れる宝石は任意で選べるため、負の宝石のうち、価値の低いものを順番に入れれば良い。

ここまでくると、愚直にシミュレートすれば良いことがわかる。
取り出す作業をA回やる、と決める。O(min(N,K))
    左からL回、右からR(=A-L)回取り出すと決める。O(min(N,K))
        P = V[:L]+V[::-1][:R] とする。（Pは取り出した宝石の価値の配列）。
        P.sort()で価値が低い順に並べて、左から価値が負のものをK-A個まで捨てる。O(NlogN)

計算量としてはO(min(N,K)**2*NlogN)で十分高速
"""

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

ans = 0
for A in range(min(N,K)+1):
    for L in range(A+1):
        R = A-L
        P = V[:L]+V[::-1][:R]
        P.sort()
        for i in range(min(K-A,A)):
            if P[i] < 0:
                P[i]=0
        ans = max(ans,sum(P))
print(ans)

Solution (Python):
N,K=map(int,input().split())
V=list(map(int,input().split()))
import heapq
turn=min(N,K)
m=0
for A in range(turn+1):
  for B in range(turn+1-A):
    h=[]
    heapq.heapify(h)
    if A>0:
      h=V[:A]+h
    if B>0:
      h=h+V[len(V)-B:]
    heapq.heapify(h)  

    ans=sum(h)
    for i in range(K-A-B):
      if h!=[]:
        f=heapq.heappop(h)
 
        if f<0:
          ans-=f
    m=max(ans,m)


    
print(m)

Solution (Python):

from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify

import itertools, bisect
import math, fractions
import sys, copy

def L(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline().rstrip())
def SL(): return list(sys.stdin.readline().rstrip())
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def LIR1(n): return [LI1() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
def LR(n): return [L() for _ in range(n)]

def perm(n, r): return math.factorial(n) // math.factorial(r)
def comb(n, r): return math.factorial(n) // (math.factorial(r) * math.factorial(n-r))

alphabets = "abcdefghijklmnopqrstuvwxyz"
ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

sys.setrecursionlimit(1000000)
dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
MOD = 1000000007
INF = float("inf")

def main():
    N, K = LI()
    V = LI()
    V2 = V + V

    ans = 0
    for k in range(1, min(K + 1, N + 1)):
        for i in range(len(V) - k, len(V) + 1):
            neg = []
            tmp = 0
            for vi in V2[i:i + k]:
                if vi < 0:
                    neg.append(vi)
                tmp += vi
            tmp -= sum(sorted(neg)[:K - k])
            ans = max(ans, tmp)

    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
def abc128_d():
    n, k = map(int, input().split())
    v = list(map(int, input().split()))
    ans = 0

    for a in range(max(1, k+1)):  
        for b in range(max(1, k-a+1)):  
            if a+b > n: break
            arr = []
            if a > 0: arr += v[:a]
            if b > 0 and a < n: arr += v[max(a, 0, n-b):]
            arr.sort()
            for j in range(max(1, a+b)):  
                if a+b+j > k: break
                score = sum(arr[j:])
                ans = max(ans, score)
                
    print(ans)

if __name__ == '__main__':
    abc128_d()

Solution (Python):
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    N,K=MI()
    V=LI()
    
    ans=0
    import heapq
    
    
    for a in range(K+1):
        for b in range(K+1):
            if a+b>min(K,N):
                break
            hq=[]
            heapq.heapify(hq)
            for i in range(a):
                heapq.heappush(hq,V[i])
            for j in range(b):
                heapq.heappush(hq,V[N-1-j])
                
            temp=0
            rem=K-(a+b)
            for i in range(a+b):
                v=heapq.heappop(hq)
                if v>=0:
                    temp+=v
                else:
                    if rem>0:
                        rem-=1
                    else:
                        temp+=v
                        
            ans=max(ans,temp)
            
    print(ans)
                
            

main()

Solution (Python):
import sys
import heapq
def input(): return sys.stdin.readline().rstrip()

def main():
    n, k = map(int, input().split())
    v = list(map(int, input().split()))
    ans = 0
    for i in range(n):
        for j in range(i, n):
            h=[0]
            heapq.heapify(h)
            count = 0
            for p in range(i-1):
                heapq.heappush(h, v[p])
                count += 1
            for m in range(j+1, n):
                heapq.heappush(h, v[m])
                count += 1
            while h[0] < 0 and count < k:
                t = heapq.heappop(h)
                count += 1
            if count <= k:
                ans = max(ans,sum(h))
    counts = n
    heapq.heapify(v)
    while h[0] < 0 and counts < k:
        t = heapq.heappop(v)
        counts += 1
    if counts <= k:
        ans = max(ans,sum(v))
    print(ans)
   
if __name__ == '__main__':
    main()

Solution (Python):
N,K =map(int, input().split())
V=list(map(int, input().split()))
res=0
for l in range(K+1):
    for r in range(K+1-l):
        if l+r>N: continue
        t=V[:l]+V[N-r:]
        t.sort()
        S=sum(t)
        for c in range(min(K-l-r,l+r)):
            if t[c]<0:
                S-=t[c]
        res=max(res,S)
print(res)

Solution (Python):
def max2(x,y):
    return x if x > y else y
def min2(x,y):
    return x if x < y else y

N, K = map(int, input().split())
V = list(map(int, input().split()))
res = 0
for l in range(K+1):
    for r in range(K+1-l):
        if l+r>N:
            continue
        temp=V[:l]+V[N-r:]
        temp.sort()
        S = sum(temp)
        for cnt in range(min2(K-l-r,l+r)):
            if temp[cnt]<0:
                S -= temp[cnt]
            else:
                break
        res = max2(res, S)
print(res)

Solution (Python):
from heapq import heappush, heappop
from random import randint
from time import time

class PriorityQueue(object):
    def __init__(self):
        self.queue = []
    def push(self, value):
        heappush(self.queue, value)
    def pop(self):
        return heappop(self.queue)
    def __len__(self):
        return len(self.queue)
    def __contains__(self, item):
        return item in self.queue

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

ans = 0


for i in range(0,m+1):

	
	lef = m-i

	hp = PriorityQueue()
	
	for j in range(0,i+1):
		if j>n :
			break

		
		for k in range(0,j):
			hp.push(v[k])

		
		for k in range(0,i-j):
			if n-1-k < j:
				break
			hp.push(v[n-1-k])

		
		for k in range(0,lef):
			if len(hp) == 0:
				break
			top = hp.pop()
			if top>=0 :
				hp.push(top)
				break

		ss = 0
		while len(hp)>0:
			ss += hp.pop()

		ans = max(ans,ss)

print(ans)

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

ans = -10**9
for back in range(n+1):
    for left in range(min(k-back+1, n+1)):
        for right in range(min(k-back-left+1, n-left+1)):
            hand = []
            hand.extend(v[:left])
            if right>0:
                hand.extend(v[-right:])
            hand.sort()
            ans = max(ans, sum(hand[back:]))

print(ans)

Solution (Python):
n,k=map(int,input().split())
v=list(map(int, input().split()))
m=min(n,k)
ans=0
for i in range(m+1): 
  for j in range(m+1-i): 
    l=[]
    l=l+v[0:i]+v[n-j:n]
    l.sort()
    for kk in range(min(k-i-j, i+j)):
      if l[kk]<0:
        l[kk]=0
    ans=max(ans, sum(l))
print(ans)

Solution (Python):
import sys
from io import StringIO
import unittest
import os


sys.setrecursionlimit(999999999)



def resolve(test_def_name=""):
    n, k = map(int, input().split())

    v_s = list(map(int, input().split()))
    v_s_rev = list(reversed(v_s))

    ans = 0
    for i in range(min(n, k) + 1):
        left = i

        for j in range(min(n, k) + 1 - i):
            right = j
            remove = min(n, k) - i - j
            if k > n:
                remove += k - n

            val_list = v_s[0:left] + v_s_rev[0:right]
            val_list.sort()
            for loop_k in range(remove):
                if len(val_list) == 0:
                    break
                if len(val_list) < loop_k + 1:
                    break
                if val_list[loop_k] >= 0:
                    break
                val_list[loop_k] = 0

            ans = max(ans, sum(val_list))

    print(ans)


class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve(sys._getframe().f_back.f_code.co_name)
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """6 4
-10 8 2 1 2 6"""
        output = """14"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """6 4
-6 -100 50 -2 -5 -3"""
        output = """44"""
        self.assertIO(test_input, output)

    def test_input_3(self):
        test_input = """6 3
-6 -100 50 -2 -5 -3"""
        output = """0"""
        self.assertIO(test_input, output)

    def test_input_4(self):
        test_input = """6 1
-100 14 1 1 -1 10"""
        output = """10"""
        self.assertIO(test_input, output)

    def test_input_5(self):
        test_input = """6 2
-100 14 1 1 -1 10"""
        output = """10"""
        self.assertIO(test_input, output)

    def test_input_6(self):
        test_input = """6 3
-100 14 1 1 -1 10"""
        output = """14"""
        self.assertIO(test_input, output)

    def test_input_7(self):
        test_input = """6 4
-100 14 1 1 -1 10"""
        output = """24"""
        self.assertIO(test_input, output)

    def test_input_8(self):
        test_input = """6 5
-100 14 1 1 -1 10"""
        output = """25"""
        self.assertIO(test_input, output)

    def test_input_9(self):
        test_input = """6 6
-100 14 1 1 -1 10"""
        output = """26"""
        self.assertIO(test_input, output)

    def test_input_10(self):
        test_input = """6 7
-100 14 1 1 -1 10"""
        output = """26"""
        self.assertIO(test_input, output)

    def test_input_11(self):
        test_input = """7 100
-100 14 -40 1 1 -30 10"""
        output = """26"""
        self.assertIO(test_input, output)

    def test_input_20(self):
        test_input = """50 100
-764207 3102944 -2816278 3249966 5606865 -5997439 4365454 1776907 -1954736 1584162 -437416 -964246 -1828950 -9965518 8636253 -6232397 3421258 -7526570 -7457280 7482600 -1554803 1252 6781335 -3233072 9958581 2263691 -3088247 -2356190 7836991 -1918599 -164787 -9946145 -4801498 3171733 4929342 -6133400 1034826 3746419 -8038615 -7593315 -6791676 5749280 -6696702 6056324 1545511 -2745311 7686370 9321150 -140154 1709122"""
        output = """111018336"""
        self.assertIO(test_input, output)



if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        
        resolve()

    else:
        
        unittest.main()

Solution (Python):
n, k = map(int, input().split())
v = list(map(int, input().split()))
reverse_v = v[::-1]
lst = [0] * (k + 1)
left = [[]]
right = [[]]
for i in range(1, n+1):
  left.append(v[:i])
  right.append(reverse_v[:i])

for cnt in range(1, k+1):
  rest = k - cnt
  total = 0
  if cnt <= n:
    for j in range(cnt+1):
      lst_j = left[j] + right[cnt-j]
      lst_j.sort()
      l = cnt
      for idx in range(cnt):
        if lst_j[idx] >= 0:
          l = idx
          break
      if l == cnt:
        value = 0
      else:
        flg = min(l, rest)
        value = sum(lst_j[flg:])
      if value > total:
        total = value
    lst[cnt] = total

ans = max(lst)
print(ans)

Solution (Python):
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for anum in range(min(N, K) + 1):
    owned = V[:anum]
    for bnum in range(min(N, K) - anum + 1):
        if bnum > 0:
            owned.append(V[-bnum])
        owned.sort()
        cdnum = K - (anum + bnum)
        total = 0
        for v in owned:
            if v < 0 and 0 < cdnum:
                cdnum -= 1
            else:
                total += v
        ans = max(ans, total)
print(ans)

Solution (Python):
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)-a+1):
        cur = V[:a] + V[N-b:]
        cur.sort()

        idx = 0
        while idx < min(K-a-b, len(cur)):
            if cur[idx] > 0: break
            else: idx += 1
        
        ans = max(ans, sum(cur[idx:]))
    
print(ans)

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

max_val = 0
left_hq = list()
left_val = 0
for left in range(N+1):
    if left > 0:
        heapq.heappush(left_hq,V[left-1])
        left_val += V[left-1]
        all_hq = copy.deepcopy(left_hq)
        all_val = left_val
        for right in range(N+1):
            if right+left > K or right+left > N :
                continue
            if right > 0:
                heapq.heappush(all_hq,V[-right])
                all_val += V[-right]
            
            temp_hq = copy.deepcopy(all_hq)
            temp_val = all_val
            for i in range(K-left-right):
                if len(temp_hq) == 0:
                    break
                else:
                    minus = heapq.heappop(temp_hq)
                    if minus > 0:
                        break
                    temp_val -= minus
                    
            if temp_val > max_val:
                max_val = temp_val
print(max_val)

Solution (Python):

from collections import deque

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

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

        q = deque(X)
        tmp = []
        for _ in range(a):
            tmp.append(q.popleft())

        for _ in range(b):
            tmp.append(q.pop())

        tmp.sort(reverse=True)
        cnt = 0
        for _ in range(K - a - b):
            if tmp and tmp[-1] < 0:
                tmp.pop()

        ans = max(ans, sum(tmp))

print(ans)

Solution (Python):
import sys
input = sys.stdin.readline

N,K = (int(x) for x in input().rstrip('\n').split())
vs = [int(x) for x in input().rstrip('\n').split()]
g = [vs[0],vs[-1]]
rest = K
for k in [K-1,K]:
  for b in range(K//2):
    t = k-b
    if t>N:
      t=N
    for i in range(t+1):
      v = []
      if i <t:
        v.extend(vs[:i])
        v.extend(vs[-(t-i):])
        for _ in range(b):
          if min(v)<0:
            v.remove(min(v))
          else:
            break
      else:
        v.extend(vs[:t])
        for _ in range(b):
          if min(v)<0:
          	v.remove(min(v))
      g.append(sum(v))
if max(g)<0:
  print(0)
else:
  print(max(g))

Solution (Python):
n , k = map(int, input().split())
v = list(map(int,input().split()))
ma = float('INF')*(-1)
m = min(n,k)
for i in range(m+1):
    for j in range(m+1-i):
        vl=v[:i]
        vr=v[n-j:]
        ans = sum(vl)+sum(vr)
        vb=vl+vr
        vb.sort()
        m2 = min(k-i-j, len(vb))
        for l in range(m2):
            if vb[l]<0:
                ans-=vb[l]
            else:
                break
        ma = max(ans,ma)
if ma<0:
    ma = 0
print(ma)

Solution (Python):
import sys

input = sys.stdin.readline


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

    ans = -float("inf")
    for t in range(min(N, K) + 1):
        s = K - t
        for l in range(t + 1):
            r = t - l
            gem = V[:l]
            gem += V[-r:] if r != 0 else []
            gem.sort()
            value = sum(gem)
            for i in range(min(s, t)):
                if gem[i] < 0:
                    value -= gem[i]
                else:
                    break
            ans = max(ans, value)

    print(ans)


if __name__ == "__main__":
    main()