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,heapify
import sys,bisect,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 i in range(k+1):
    pick = i; back = k-i
    for j in range(pick+1):
        l = j; r = pick-j
        q = deque(a)
        
        now = []
        while q and l > 0:
            now.append(q.popleft())
            l -= 1
        while q and r > 0:
            now.append(q.pop())
            r -= 1
        now.sort(); ln = len(now)
        ans = sum(now)
        res = max(res, ans)
        for i in range(back):
            if i >= ln: continue
            ans -= now[i]
            res = max(res, ans)
print(res)

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

ans = 0
for l in range(N):
    if l > K: break
    for r in range(N-l+1):
        if l+r > K: break
        vs = V[:l] + (V[-r:] if r>0 else [])
        vs.sort()
        k = K-l-r
        t = 0
        for v in vs:
            if v < 0 and k > 0:
                k -= 1
                continue
            t += v
        ans = max(ans,t)
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:
            continue
        k = K - (l + r)
        if k < 0:
            continue

        A = V[:l] + V[N - r:]
        A.sort(reverse=True)
        while k > 0 and A and A[-1] < 0:
            A.pop()
            k -= 1
        ans = max(ans, sum(A))
print(ans)

Solution (Python):
n,k=map(int,input().split())
v=list(map(int,input().split()))
ans=0
for a in range(min(k,n)+1):
  for b in range(min(k,n)-a+1):
    t=v[:a]
    t+=v[n-b:]
    t.sort()
    for i in range(k-(a+b)):
      if len(t) and t[0]<0:
        t.pop(0)
    ans=max(ans,sum(t))
print(ans)

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

ans = 0
for left in range(min(N, K) + 1):
    for right in range(min(N - left, K - left) + 1):
        tmp = V[:left] + V[N - right:]
        tmp.sort()
        score = 0
        count = K - left - right
        for i in tmp:
            if count <= 0:
                score += i
            else:
                if i < 0:
                    count -= 1
                else:
                    score += i
        
        ans = max(ans, score)

print (ans)

Solution (Python):
import bisect


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

res = 0
for toru in range(0, min(k, n) + 1):
    tumeru = k - toru
    for migi in range(0, toru + 1):
        hidari = toru - migi
        ans = v[0:hidari] + v[n - migi:n]        
        ans = sorted(ans)
        ind = bisect.bisect_left(ans, 0)
        res = max((sum(ans) - sum(ans[0:min(ind, tumeru)])), res)
print(res)

Solution (Python):
n,k = map(int,input().split())
lis = list(map(int,input().split()))
ans = 0
for i in range(n):
    for j in range(n-i+1):
        num = lis[:i]
        if j > 0:
            num += lis[-j:]
        if len(num) <= k:
            cnt = min(len(num),k-len(num))
            num.sort()
            for h in range(cnt):
                num[h] = max(0,num[h])
            ans = max(ans,sum(num))
print(ans)

Solution (Python):
N,K = map(int,input().split())
V = [0] + list(map(int,input().split())) + [0]
m = min(N,K)

A = []
ans = 0



for i in range(m+1):
    if i == 0:
        pass
    else:
        A.append(V[i])
    B = []
    for j in range(m-i+1):
        if j == 0:
            pass
        else:
            B.append(V[N-j+1])
        C = A+B
        C.sort()
        a = sum(C)
        for k in range(len(C)):
            if C[k] < 0 and k < K-(i+j):
                a -= C[k]
        ans = max(ans,a)

print(ans)

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from heapq import heapify, heappop, heappush 
def main():
    N, K = map(int, readline().split())
    V = [int(i) for i in readline().split()]
    A = V[::-1]
    ans = 0
    for l in range(K+1):
        for r in range(K+1-l):
            if l+r>N:
                continue
            rest = K-(l+r)
            hp = V[:l] + A[:r]
            heapify(hp)
            for _ in range(rest):
                if len(hp)==0:
                    break
                v = heappop(hp)
                if v > 0:
                    heappush(hp, v)
            ans = max(ans, sum(hp))
    print(ans)
if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
N,K=map(int,input().split())
V=list(map(int,input().split()))
res=0
for i in range(min(K,N)+1):
    for L in range(i+1):
        R=i-L
        li=[]
        for j in range(L):
            li.append(V[j])
        for j in range(R):
            li.append(V[N-j-1])
        li.sort()
        s=sum(li)
        for k in range(min(K-i,len(li))):
            if(li[k]<0):
                s-=li[k]
            else:
                break
        res=max(s,res)
print(res)

Solution (Python):
n,k,*l=map(int,open(0).read().split())
v,m=0,min(n,k)+1
from bisect import*
for i in range(m):
  for j in range(m-i): s=sorted(l[:i]+l[n-j:]); v=max(v,sum(s[min(bisect(s,-1),k-i-j):]))
print(v)

Solution (Python):
f=lambda:map(int,input().split())
n,k=f()
l=list(f())
v=0
m=min(n,k)
from bisect import *
for i in range(m+1):
  for j in range(m+1-i):
    s=sorted(l[:i]+l[n-j:])
    v=max(v,sum(s[min(bisect_left(s,0),k-i-j):]))
print(v)

Solution (Python):
import bisect
N,K= map(int,input().split())
V = list(map(int,input().split()))
sortedV = sorted(V)
rV = V[::-1]

ans = -10**10
for nout in range(K+1):
    nin = K-nout
    if nout >= N:
        cand = sortedV
        ind = bisect.bisect_left(cand,0)
        ind = min(ind,nin)
        ans = max(ans, sum(cand[ind:]))
    else:
        for nleft in range(nout+1):
            nright = nout - nleft
            cand = V[:nleft] + rV[:nright]
            cand.sort()
            ind = bisect.bisect_left(cand,0)
            ind = min(ind,nin)
            ans = max(ans, sum(cand[ind:]))
print(ans)

Solution (Python):
N, K = map(int, input().split())
V = list(map(int, input().split()))
 
ans = 0
for a_plus_b in range(min(N, K) + 1): 
    for a in range(a_plus_b + 1):
        b = a_plus_b - a
        gems = V[:a] 
        if b > 0:
            gems += V[-b:] 
        gems.sort()
        negative_gems = [g for g in gems if g < 0]
        ans = max(ans, sum(gems) - sum(negative_gems[:K - a_plus_b])) 
print(ans)

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

ans = 0
for a_plus_b in range(min(N, K) + 1):
    for a in range(a_plus_b + 1):
        b = a_plus_b - a
        gems = V[:a]
        if b > 0:
            gems += V[-b:]
        gems.sort()
        negative_gems = [g for g in gems if g < 0]
        ans = max(ans, sum(gems) - sum(negative_gems[:K - a_plus_b]))
print(ans)

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

n, k = map(int, readline().split())
v = list(map(int, readline().split()))
ans = -float('inf')
nk = min(n, k)
for a in range(nk + 1):
    for b in range(nk - a + 1):
        vv = v[:a] + v[n - b:]
        if k - a - b >= 0:
            vv.sort()
            cnt = 0
            for check in vv[:k - a - b]:
                if check >= 0:
                    break
                cnt += check
            ans = max(ans, sum(vv) - cnt)
print(ans)

Solution (Python):
import heapq
from collections import deque
from copy import deepcopy

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

dq = deque()
dq.extend(V)
INF = 10**10

ans = -INF
for i in range(k+1):
  for j in range(k+1-i):           
    que = deepcopy(dq)
    a = []    
    
    if i+j <= n:
      for l in range(i):      
        heapq.heappush(a,que.popleft())
      for r in range(j):
        heapq.heappush(a,que.pop())    
      
      ans = max(ans,sum(a))        
      for ki in range(k-i-j):   
        if len(a) > 0:
          heapq.heappop(a)
        ans = max(ans,sum(a))        
        
if ans != -INF:          
  print(ans)
else:
  print(0)

Solution (Python):
N, K = map(int, input().split())
V = list(map(int, input().split()))
lst = []
take = min(N, K)
ans = 0

for i in range(take+1):
    for j in range(take - i +1):
        lst = V[:i] + V[N - j:]
        lst.sort()
        cnt = 0
        for t in lst:
            if t < 0:
                cnt += 1
        d = min(cnt, K - ( i + j))
        del lst[:d]
        ans = max(ans, sum(lst))

print(ans)

Solution (Python):
import sys
import bisect
N, K = map(int, sys.stdin.readline().split())
V = list(map(int, sys.stdin.readline().split()))


sum_list = [V[0]]
for i in range(1, N):
    add = V[i] + sum_list[-1]
    sum_list.append(add)

ans = 0

max_take = min(N, K)

for A in range(max_take + 1):
    for B in range(max_take - A + 1):
        if A > 0 and B > 0:
            list = V[:A] + V[N - B:]
            total_sum = sum(list) 
            list.sort()
            n = bisect.bisect_left(list, 0)
            if n <= K - (A + B):
                total_sum -= sum(list[:n])
            else:
                total_sum -= sum(list[:K - (A + B)])
        elif A == 0 and B > 0:
            list = V[N - B:]
            total_sum = sum(list) 
            list.sort()
            n = bisect.bisect_left(list, 0)
            if n <= K - (A + B):
                total_sum -= sum(list[:n])
            else:
                total_sum -= sum(list[:K - (A + B)])
        elif A > 0 and B == 0:
            list = V[:A]
            total_sum = sum(list) 
            list.sort()
            n = bisect.bisect_left(list, 0)
            if n <= K - (A + B):
                total_sum -= sum(list[:n])
            else:
                total_sum -= sum(list[:K - (A + B)])
        else:
            continue
        
        
        
        ans=max(ans,total_sum)
            
print(ans)

Solution (Python):
import sys
import bisect
N, K = map(int, sys.stdin.readline().split())
V = list(map(int, sys.stdin.readline().split()))

ans = 0

max_take = min(N, K)

for A in range(max_take + 1):
    for B in range(max_take - A + 1):
        
        list = V[:A] + V[N - B:]
        total_sum = sum(list) 
        list.sort()
        n = bisect.bisect_left(list, 0)
        if n <= K - (A + B):
            total_sum -= sum(list[:n])
        else:
            total_sum -= sum(list[:K - (A + B)])
        '''
        elif A == 0 and B > 0:
            list = V[N - B:]
            total_sum = sum(list)
            list.sort()
            n = bisect.bisect_left(list, 0)
            if n <= K - (A + B):
                total_sum -= sum(list[:n])
            else:
                total_sum -= sum(list[:K - (A + B)])
        elif A > 0 and B == 0:
            list = V[:A]
            total_sum = sum(list)
            list.sort()
            n = bisect.bisect_left(list, 0)
            if n <= K - (A + B):
                total_sum -= sum(list[:n])
            else:
                total_sum -= sum(list[:K - (A + B)])
        else:
            continue'''
        
        if total_sum > ans:
            ans = total_sum
            
print(ans)

Solution (Python):
import sys
import bisect
N, K = map(int, sys.stdin.readline().split())
V = list(map(int, sys.stdin.readline().split()))


sum_list = [V[0]]
for i in range(1, N):
    add = V[i] + sum_list[-1]
    sum_list.append(add)

ans = 0

max_take = min(N, K)

for A in range(max_take + 1):
    for B in range(max_take - A + 1):
        if A > 0 and B > 0:
            list = V[:A] + V[N - B:]
            total_sum = sum(list) 
            list.sort()
            n = bisect.bisect_left(list, 0)
            if n <= K - (A + B):
                total_sum -= sum(list[:n])
            else:
                total_sum -= sum(list[:K - (A + B)])
        elif A == 0 and B > 0:
            list = V[N - B:]
            total_sum = sum(list) 
            list.sort()
            n = bisect.bisect_left(list, 0)
            if n <= K - (A + B):
                total_sum -= sum(list[:n])
            else:
                total_sum -= sum(list[:K - (A + B)])
        elif A > 0 and B == 0:
            list = V[:A]
            total_sum = sum(list) 
            list.sort()
            n = bisect.bisect_left(list, 0)
            if n <= K - (A + B):
                total_sum -= sum(list[:n])
            else:
                total_sum -= sum(list[:K - (A + B)])
        else:
            continue
        
        
        
        if total_sum > ans:
            ans = total_sum
            
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
N,K = map(int,input().split())
V = list(map(int,input().split()))
D = []
ans = 0
for i in range(K+1):
    for j in range(K-i+1):
        if i + j > N:
            break
        D.append(V[:i]+V[N-j:])
for d in D:
    for x in range(K-len(d)):
        if d==[]:
            break
        elif min(d)<0:
            d.pop(d.index(min(d)))

        elif min(d)>0:
            break        
    if d!=[]:
        s = sum(d)
        if s>0 and s>ans:
            ans = s
print(ans)

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

D = []
ans = []

for i in range(K+1):
    for j in range(K-i+1):
        if i + j > N:
            break
        D.append(V[:i]+V[N-j:])

for d in D:
    for x in range(K-len(d)):
        if d==[]:
            break
        elif min(d)<0:
            d.pop(d.index(min(d)))

        elif min(d)>0:
            break
        
    if d==[]:
        ans.append(0)
    elif sum(d)>0:
        ans.append(sum(d))

if max(ans)>0:
    print(max(ans))

else:
    print(0)

Solution (Python):
import copy

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

result = 0

for i in range(min(N,K)+1):
    
    for sp in range(i+1): 
        
        
        tmp = []
        V_tmp = copy.copy(V)
        
        tmp.extend(V_tmp[:sp]) 
        
        tmp.extend(V_tmp[N-(i-sp):]) 
        
        
        tmp = sorted(tmp)
        value = sum(tmp)
        
        for ret in range(0, min(K-i,i)): 
            if ret < i:
                
                if tmp[ret] < 0:
                    value -= tmp[ret]
                    
            else:
                break
        result = max(result,value)
            

print(result)

Solution (Python):
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()

        sum_ = sum(jwl)
        for i in range(min(rmv, len(jwl))):
            if jwl[i] >= 0:
                break

            sum_ -= jwl[i]

        max_ = max(max_, sum_)


print(max_)

Solution (Python):
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+1):
            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()

Solution (Python):
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 l in range(k-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)

Solution (Python):
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 l in range(k-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)

Solution (Python):
import heapq

res=0
n,k=map(int,input().split())
v=list(map(int,input().split()))
r=min(n,k)
for a in range(r+1):
    for b in range(r-a+1):
        d=v[:a]
        d.extend(v[n-b:])
        s=sum(d)
        heapq.heapify(d)

        l=k-(a+b) 
        for _ in range(l):
            if not d:
              break
            t=heapq.heappop(d)
            if t<0:
               s-=t
            else:
                break
        if s>res:
            res=s
print(res)

Solution (Python):
import heapq

n,k=map(int,input().split())
v=list(map(int,input().split()))
s=-10**7-1

if n>k:
    for l in range(k//2+1):
        for i in range(k+1-l):
            d=v[:i]
            d.extend(v[(n-k+l+i):])
            heap=heapq.heapify(d)
            res=sum(d)
            for j in range(l):
                t=heapq.heappop(d)
                if t<0:
                    res-=t
                else:
                    break
            if s<res:
                s=res
else:
    for l in range(n+1):
        for i in range(n-l+1):
            d=v[:i]
            d.extend(v[(l+i):])
            heap=heapq.heapify(d)
            res=sum(d)
            for j in range(k-(n-l)):
                if not d:
                    break
                t=heapq.heappop(d)
                if t<0:
                    res-=t
                else:
                    break
            if s<res:
                s=res

        
if s<0:
    print(0)
else:
    print(s)

Solution (Python):
from collections import deque
from heapq import heappush, heappop
from copy import deepcopy

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

dq = deque(v)

ans = 0
for ab in range(k + 1):
    cd = k - ab
    for a in range(ab + 1):
        hp = []
        cp = deepcopy(dq)

        b = ab - a
        for _ in range(a):
            if cp:
                val = cp.popleft()
                heappush(hp, val)
        for _ in range(b):
            if cp:
                val = cp.pop()
                heappush(hp, val)

        for _ in range(cd):
            if not hp or hp[0] >= 0:
                break
            heappop(hp)

        ans = max(ans, sum(hp))

print(ans)

Solution (Python):
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(1,K+1):
    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)

Solution (Python):
n, k = [int(x) for x in input().split()]
v_list = [int(x) for x in input().split()]

stop = min(n, k)

ans = 0
for a in range(stop + 1):
    a_list = v_list[:a]
    for b in range(stop + 1 - a):
        b_list = v_list[n-b:]
    
        temp_list = a_list + b_list
        temp_list.sort(reverse=True)

        for _ in range(k - a - b):
            if len(temp_list) == 0 or temp_list[-1] >= 0:
                break
            temp_list.pop()

        temp = sum(temp_list)
        if ans < temp:
            ans = temp
print(ans)

Solution (Python):
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 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")


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]


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(min(k-a+1,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(ans)

Solution (Python):
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
    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)

Solution (Python):
from collections import deque
import heapq
def f(d,n):
    a = list(d)
    heapq.heapify(a)
    while n > 0 and len(a) > 0:
        tmp = heapq.heappop(a)
        if tmp >= 0:
            heapq.heappush(a,tmp)
            break
        n -= 1
    return sum(a)


N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for i in range(1,min(N,K)+1):
    d = deque()
    for k in range(i):
        d.append(V[k])
    ans = max(ans,f(d,K-i))
    for k in range(i):
        d.pop()
        d.appendleft(V[N-1-k])
        ans = max(ans,f(d,K-i))
print(ans)

Solution (Python):
import sys

input_methods=['clipboard','file','key']
using_method=0
input_method=input_methods[using_method]

IN=lambda : map(int, input().split())
LIN=lambda : list(IN())
mod=1000000007



def main():
	
	n, k = IN()
	dq = LIN()
	rdq = dq[::-1]
	
	max_v=0
	for left_get in range(k+1):
		for right_get in range(max(k-left_get+1,1)):
			if left_get+right_get>n:
				continue
			elif left_get==0 and right_get==0:
				continue
			nokori=k-left_get-right_get
			l=dq[:left_get]
			r=rdq[:right_get]
			
			dd=(l+r)
			dd.sort(reverse=True)
			for _ in range(nokori):
				if dd[-1]>= 0:
					break
				dd.pop()
				if len(dd)==0:
					break
			r=sum(dd)
			max_v=max(max_v, r)
	print(max_v)
		
		
	
	

isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		
			
	ret = main()
	if ret is not None:
		print(ret)

Solution (Python):
from collections import deque
import heapq
def f(d,n):
    a = list(d)
    heapq.heapify(a)
    while n > 0 and len(a) > 0:
        tmp = heapq.heappop(a)
        if tmp >= 0:
            heapq.heappush(a,tmp)
            break
        n -= 1
    return sum(a)
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for i in range(1,min(N,K)+1):
    d = deque()
    for k in range(i):
        d.append(V[k])
    ans = max(ans,f(d,K-i))
    for k in range(i):
        d.pop()
        d.appendleft(V[N-1-k])
        ans = max(ans,f(d,K-i))
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)+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,K-a-b)):
            if v[i]<0:
                value=value-v[i]
            else:
                break
        ans=max(ans,value)
print(ans)

Solution (Python):
N,K=map(int,input().split())
V=list(map(int,input().split()))
ans=0
if 2*N<=K:
    for i in V:
        if i>=0:
            ans+=i
else:
    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)

Solution (Python):


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+1-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)

Solution (Python):
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    N, K = map(int, readline().split())
    V = list(map(int, readline().split()))
    max_value = 0
    for L in range(N+1):
        for R in range(N+1):
            if L+R>K:
                break
            if L+R>N:
                break
            get = V[:L]
            if R>0:
                get += V[-R:]
            get.sort()
            rest = K - (L+R)
            minus = sum((1 if x<0 else 0 for x in get))
            if minus>rest:
                value = sum(get[rest:])
            else:
                value = sum((x for x in get if x>0))
            if value>max_value:
                max_value=value
    print(max_value)

if __name__ == '__main__':
    main()

Solution (Python):
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for i in range(K+1):
  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]
    ans = max(ans, sum(bag)+tmp)
print(ans)

Solution (Python):

'''
左からL個、右からR個、取り出す。
取り出す回数は操作回数上限のK回なので、最大K個取り出せる。
操作はK回まで行えるので、操作回数がKより小さくてもOK。
求めるのは、価値の最大値なので、マイナスの宝石は、筒に戻す。
筒に戻せる上限は、下記１と２の小さい値min
１．操作回数制限：K-L-R、操作回数の上限から、LとRを取り出した回数を引く
２．宝石個数制限：手持ちは、L+R個なので、これ以上は戻せない
'''
N, K = map(int, input().split())
*V, = map(int, input().split())
ans = 0

for l in range(K + 1):
	for r in range(K - l + 1):
    
		inHand = []
		if l + r > N:  
			break
		
		inHand = V[: l]
		inHand.extend(V[N - r:])
		tmp = sum(inHand)  
        
		
		inHand.sort()
		for i in range(min(K - l - r, l + r)):
			if inHand[i] >= 0:
				break
			tmp -= inHand[i]
		ans = max(ans, tmp)

print(ans)