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):

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)

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

for i in range(N+1):
    for j in range(N+1):
        if i+j>N:
            continue
        
        l = []
        
        for k in range(i):
            l.append(V[k])
        
        for k in range(j):
            l.append(V[N-1-k])
        
        if len(l)>K:
            continue
        
        l.sort()
        cnt = K-len(l)
        now = 0
        
        while cnt>0 and now<len(l) and l[now]<0:
            cnt -= 1
            now += 1
        
        ans = max(ans, sum(l[now:]))

print(ans)

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

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

        
        leftVal = self.V[fromIncl]
        if leftVal>=0:
            self.posSum+=leftVal
        else:
            bipos = bisect_left(self.negPreSum, -leftVal)
            self.negPreSum.insert(bipos, -leftVal)

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

        if canCallNext:
            self.rec(fromIncl+1, toIncl)
        
        if leftVal>=0:
            self.posSum-=leftVal
        else:
            self.negPreSum.pop(bipos)
        
        
        rightVal = self.V[toIncl]
        if rightVal>=0:
            self.posSum+=rightVal
        else:
            bipos = bisect_left(self.negPreSum, -rightVal)
            self.negPreSum.insert(bipos, -rightVal)

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

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

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

        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")

Solution (Python):


def solve(string):
    n, k, *v = map(int, string.split())
    ans = 0
    for i in range(k + 1):
        for j in range(k - i + 1):
            base = sorted(v[:i] + v[max(n - k + i + j, i):])
            ans = max(ans, sum([b for l, b in enumerate(base) if b >= 0 or j <= l]))
    return str(ans)


if __name__ == '__main__':
    print(solve('\n'.join([input(), input()])))

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

ans = 0
for x in range(N+1):
    for y in range(N+1):
        if x+y > N or x+y > K:
            break
        rest = min(K-x-y, x+y)
        As = Vs[:x] + Vs[N-y:]
        As.sort()
        score = sum(As)
        for i in range(rest):
            if As[i] < 0:
                score -= As[i]
        ans = max(ans, score)

print(ans)

Solution (Python):
def solve():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    V *= 2
    ans = 0
    for i in range(N+1):
        for j in range(N-1,2*N):
            num = j-i+1
            if num>K or num>N or num == 0:
                continue
            lis = V[i:j+1]
            lis.sort()
            margin = K-num
            m = sum(lis)
            k = 0
            while k < margin and k < num and lis[k]<0 :
                m -= lis[k]
                k += 1
            ans = max(ans,m)
    return ans
print(solve())

Solution (Python):

def inputlist(): return [int(k) for k in input().split()]

N,K = inputlist()
V = inputlist()
n = min(N,K)
ans = 0
from collections import deque
for a in range(n+1):
    for b in range(n+1):
        li = []
        if a+b > n:
            continue
        c = K-(a+b)
        que = deque(V)
        for i in range(a):
            k = que.popleft()
            li.append(k)
        for j in range(b):
            s = que.pop()
            li.append(s)
        li.sort()
        index = 0
        for i in range(len(li)):
            if li[i] < 0:
                index +=1
        na = min(index,c)
        suma = sum(li[na:])
        ans = max(ans,suma)

print(ans)

Solution (Python):
n,k = map(int,input().split())
V = list(map(int,input().split()))
Vi = V[::-1]
t = min(n,k)
ans = 0
for i in range(1,t+1):
    for a in range(0,i+1):
        b = i-a
        houseki = V[0:a] + Vi[0:b]
        houseki.sort()
        tmp=sum(houseki)
        for idx,val in enumerate(houseki):
            if idx==k-i:break
            if val<0:tmp-=val
        ans = max(ans,tmp)
print(ans)

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


answer=0
for i in range(K+1):
  if i>N: break
  
  take_cand=[]
  if i==N:
    take_cand=[vlist]
  else:
    for j1 in range(i+1):
      j2=i-j1
      take_cand.append(vlist[:j1]+vlist[N-j2:])
  
  
  for take in take_cand:
    take.sort(reverse=True)
    for _ in range(K-i):
      if len(take)>0 and take[-1]<0:
        take.pop()
    
    answer=max(sum(take),answer)

print(answer)

Solution (Python):
import copy,heapq

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

ans=0
left=copy.copy(V)
for i in range(1,N):
    left[i]+=left[i-1]
right=copy.copy(V)
for i in range(1,N):
    right[-i-1]+=right[-i]
for i in range(0,N+1):
    for j in range(0,N-i+1):
        dispose=K-i-j
        if 0>dispose:
            continue
        test=0
        q=[]
        if i>0:
            test+=left[i-1]
            q+=V[:i]
        if j>0:
            test+=right[-j]
            q+=V[N-j:N]

        heapq.heapify(q)
        while dispose>0 and q:
            x=heapq.heappop(q)
            if 0>x:
                test-=x
                dispose-=1
            else:
                break
        ans=max(ans,test)

print(ans)

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

Solution (Python):
n,k = map(int,input().split())
v = list(map(int,input().split()))
ma = 0
kaisu = min(n,k)
for a in range(kaisu+1):
    for b in range(kaisu-a+1):
        push = k-(a+b)
        li = v[:a]+v[n-b:]
        li.sort(reverse=True)
        for c in range(push):
            if li:
                if li[-1] < 0:
                    li.pop()
        ma = max(ma,sum(li))
print(ma)

Solution (Python):
def main():
    n, k = [int(e) for e in input().split()]
    V = [int(e) for e in input().split()]

    ans = 0
    vc = min(n, k)
    for vci in range(1, vc + 1):
        for vcii in range(vci + 1):
            Hand = []
            for li in range(vcii):
                Hand.append(V[li])

            for ri in range(vci - vcii):
                Hand.append(V[-ri - 1])

            Hand.sort()
            for i in range(min(k - vci, len(Hand))):
                if Hand[i] < 0:
                    Hand[i] = 0

            ans = max(sum(Hand), ans)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
n,k = map(int,input().split())
V = list(map(int,input().split()))
ans = 0
for i in range(n+1):
    for j in range(n+1-i):
        removed = V[:i] + V[n-j:]
        if len(removed) > k:break
        removed.sort()
        get = sum(removed)
        for l in range(min(k-len(removed),len(removed))):
            if removed[l] >= 0:break
            get -= removed[l]
        ans = max(ans,get)
print(ans)

Solution (Python):
def main():
    n, k = map(int, input().split())
    v = [int(x) for x in input().split()]
    
    ans = 0
    r = min([n, k])
    for i in range(r+1):
        for j in range(r+1-i):
            sub = sum(v[:i])+sum(v[n-j:n])
            minus = []
            for l in range(n):
                if (l < i or n-j < l) and v[l] < 0:
                    minus.append(v[l])
            minus.sort()
            sub -= sum(minus[:min([len(minus), k-i-j])])
            if ans < sub:
                ans = sub
        
    print(ans)

if __name__ == "__main__":
    main()

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

def main():
    n, k = map(int, input().split())
    v = deque([int(x) for x in input().split()])

    left_plus = 0
    left_minus_count = 0
    left_minus_list = []
    
    ans = 0
    sub = 0
    minus_list = []
    minus_count = 0
    heapq.heapify(minus_list)
    for i in range(n-1, max([-1, n-k-1]), -1):
        if v[i] >= 0:
            sub += v[i]
        else:
            heapq.heappush(minus_list, -v[i])
            minus_count += 1
        while n-i+minus_count > k and minus_list:
            sub -= heapq.heappop(minus_list)
            minus_count -= 1
        if n-i+minus_count > k:
            break
        if ans < sub:
            ans = sub
    
    for i in range(min([n, k])):
        if v[i] >= 0:
            left_plus += v[i]
        else:
            left_minus_list.append(-v[i])
            left_minus_count += 1
        
        sub = left_plus
        minus_count = left_minus_count
        minus_list = copy.deepcopy(left_minus_list)
        heapq.heapify(minus_list)
        while i+minus_count+1 > k and minus_list:
            minus_count -= 1
            sub -= heapq.heappop(minus_list)
        if i+minus_count+1 <= k and ans < sub:
            ans = sub
        sub = left_plus
        minus_count = left_minus_count
        minus_list = copy.deepcopy(left_minus_list)
        heapq.heapify(minus_list)
        for j in range(n-1, max([i, n-k+i+1]), -1):
            if v[j] >= 0:
                sub += v[j]
            else:
                minus_count += 1
                heapq.heappush(minus_list, -v[j])
            while minus_count+i+n-j+1 > k and minus_list:
                minus_count -= 1
                sub -= heapq.heappop(minus_list)
            
            if i+(n-j)+minus_count+1 > k:
                break
            if ans < sub:
                ans = sub
        
        
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
def main():
    n,k = map(int,input().split())
    v = list(map(int,input().split()))
    m = 0
    for i in range(k+1):
        if i > n:
            rem = k-n
            have = v
            while len(have)>0 and have[0]<0 and rem>0:
                    have.pop(0)
                    rem -= 1
            s = sum(have)
            if m<s:
                m = s
            break
        for j in range(i+1):
            l=j
            r=i-l
            have = v[0:l]+v[n-r:n]
            rem = k-i
            have = sorted(have)
            if len(have)==0:
                s = 0
            else:
                while len(have)>0 and have[0]<0 and rem>0:
                    have.pop(0)
                    rem -= 1
                s = sum(have)
            if m<s:
                m = s
    print(m)

        

if __name__ == "__main__":
    main()

Solution (Python):
N,K=map(int,input().split())
v=list(map(int,input().split()))
ans=0

for i in range(min(N,K)+1): 
    for a in range(i+1): 
        b=i-a 
        val=sorted(v[:a]+v[N-b:]) 
        s=sum(val)

        for j in range(0,min(K-i,len(val))): 
            if j<len(val):

                if val[j]<0: 
                    s-=val[j]
            else:
                break

        ans=max(ans,s)
print(ans)

Solution (Python):
n,k = map(int,input().split())
v = list(map(int,input().split()))
r = min(n,k)
ans = -10**10
for i in range(0,r+1):
  for a in range(i+1):
    b = i - a
    val = sorted(v[:a]+v[(n-b):])
    s = sum(val)
    for j in range(min(k-i,len(val))):
      if val[j] < 0:
        s -= val[j]
      else:
        break
    ans = max(ans,s)
print(ans)

Solution (Python):
def main():
    import sys
    import heapq
    from copy import deepcopy
    from collections import deque
    sys.setrecursionlimit(10 ** 6)
    input = sys.stdin.readline
    N, K = [int(x) for x in input().strip().split()]
    V = [int(x) for x in input().strip().split()]
    ans = -float('inf')
    for l in range(min(N, K)+1):
        for r in range(min(N, K)-l+1):
            vt = sorted(V[:l] + V[N-r:])
            c = 0
            i = 0
            for i in range(len(vt)):
                if c == (K-l-r):
                    break
                if vt[i] < 0:
                    vt[i] = 0
                    c += 1
                else:
                    break
            ans = max(ans, sum(vt))

    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):

import sys


def solve(N: int, K: int, V: "List[int]"):

    sum_l = []
    for lk in range(min(N+1, K+1)):
        rk = min(N-lk, K - lk)
        if rk>0:
            q = V[:lk][::-1] + V[-rk:]
        else:
            q = V[:lk][::-1]
        
        m = 0
        sum_=0
        mn = K - (lk+rk)


        for i in range(len(q)):
            q_ = q[i:]
            m = i+mn
            q_s = sorted(q_)
            for x in range(len(q_s)):
                if (q_s[x]<0)&(m>0):
                    m-=1
                else:
                    break
            sum_ = sum(q_s[i+mn-m:])
            sum_l.append(sum_)

    
    print(max(sum_l))
    return



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    K = int(next(tokens))  
    V = [int(next(tokens)) for _ in range(N)]  
    solve(N, K, V)

if __name__ == '__main__':
    main()

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):
        hand = V[:A]+V[N-B:]
        hand.sort()
        i = 0
        while i < K-A-B and i < len(hand) and hand[i] < 0:
            hand[i] = 0
            i += 1
        ans = max(ans, sum(hand))
print (ans)

Solution (Python):
def main():
    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):
            chk=v[:a]+v[n-b:]
            chk.sort()
            x,s=0,sum(chk)
            while x<k-(a+b) and len(chk)>x:
                s-=min(0,chk[x])
                x+=1
            ans=max(ans,s)
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):

import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, K = lr()
V = lr()
scores = set()
limit = min(N, K)
for i in range(limit+1): 
    for j in range(limit-i+1): 
        stone = V[:i] + V[N-j:]
        stone.sort()
        result = sum(stone)
        scores.add(result)
        for k in range(min(len(stone), K-(i+j))): 
            if stone[k] >= 0:
                break
            result -= stone[k]
            scores.add(result)

answer = max(scores)
print(answer)

Solution (Python):

import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, K = lr()
V = lr()
answer = 0
limit = min(N, K)
for i in range(limit+1): 
    for j in range(limit-i+1): 
        stone = V[:i] + V[N-j:]
        stone.sort()
        result = sum(stone)
        if result > answer:
            answer = result
        for k in range(min(len(stone), K-(i+j))): 
            if stone[k] > 0:
                break
            result -= stone[k] 
            if result > answer:
                answer = result

print(answer)

Solution (Python):

import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, K = lr()
V = lr()
scores = [0]
limit = min(N, K)
for i in range(limit+1): 
    for j in range(limit-i+1): 
        stone = V[:i] + V[N-j:]
        stone.sort()
        result = sum(stone)
        scores.append(result)
        for k in range(min(len(stone), K-(i+j))): 
            if stone[k] > 0:
                break
            result -= stone[k] 
            scores.append(result)

answer = max(scores)
print(answer)

Solution (Python):
def main():
    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):
            chk=v[:a]+v[n-b:]
            chk.sort()
            x,s=0,sum(chk)
            while x<k-(a+b) and len(chk)>x:
                s-=min(0,chk[x])
                x+=1
            ans=max(ans,s)
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):

import sys
sys.setrecursionlimit(10 ** 7)

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))


N, K = lr()
V = lr()
answer = 0
V = V[::-1] + V[::-1]
for x in range(K+1):
    
    x = min(x, N)
    for i in range(N-1, N-1+x+1):
        take = V[i-x+1:i+1]
        take.sort(reverse=True)
        result = sum(take)
        if result > answer:
            answer = result
        for j in range(K-x):
            if take:
                result -= take.pop()
                if result > answer:
                    answer = result

print(answer)

Solution (Python):

import sys
input = sys.stdin.readline










from collections import deque
import heapq

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

ans = 0

maxPop = min(N,K)

for li in range(maxPop+1):
    
    for ri in range(maxPop+1-li):
        
        D = deque(V)
        jew = [] 

        
        maxPush = K - (ri+li)
        
        for i in range(li):
            jew.append(D.popleft())
        
        for i in range(ri):
            jew.append(D.pop())
        
        jew.sort()
        
        for i in range(min(maxPush, len(jew))):
            if jew[i] < 0:
                jew[i] = 0
        
        ans = max(ans,sum(jew))

print(ans)

Solution (Python):
import sys

input = sys.stdin.readline


def main():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    _V = V[::-1]

    ans = 0
    for k in range(K + 1):
        n_pop = min(k, N)
        n_push = K - n_pop
        for i in range(n_pop + 1):
            l, r = i, n_pop - i
            L = V[:l] + _V[:r]
            L.sort()
            for j in range(min(n_pop, n_push)):
                if L[j] < 0:
                    L[j] = 0
                else:
                    break
            v = sum(L)
            if v > ans:
                ans = v

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):

n, k = map(int, input().split())
v = list(map(int, input().split()))
q = []
ans = 0
for a in range(min(n, k) + 1):
    for b in range(min(n, k) - a + 1):
        
        if a == 0:
            pass
        else:
            q.extend(v[:a])
        if b == 0:
            pass
        else:
            q.extend(v[-b:])
        q.sort()
        pick = k - (a + b)
        for i in range(min(pick, len(q))):
            
            if q[0] < 0:
                q.reverse()
                q.pop()
                q.reverse()
            else:
                break
        s = sum(q)
        
        if ans < s:
            ans = s
        q.clear()
print(ans)

Solution (Python):
import sys
input = lambda: sys.stdin.readline().rstrip()
input_nums = lambda: list(map(int, input().split()))
from collections import deque

def main():
    N, K = input_nums()
    V = input_nums()
    maxv = 0
    for total in range(min(N, K)+1):
        for a in range(total+1):
            D = deque(V)
            gems = []
            b = total - a
            for i in range(a):
                gems.append(D.pop())
            for i in range(b):
                gems.append(D.popleft())
            gems.sort(reverse=True)
            d = K - (a+b)
            for i in range(d):
                if len(gems) > 0:
                    a = gems.pop()
                    if a < 0:
                        continue
                    else:
                        gems.append(a)
                        break
            maxv = max(maxv, sum(gems))
    print(maxv)

if __name__ == '__main__':
    main()

Solution (Python):


import sys

from collections import deque                









import math

def main():
    mod = 10000007                  
    inf = float('inf')
    input = sys.stdin.readline      
    sys.setrecursionlimit(10**6)    
    def ii():  return int(input())
    def mi():  return map(int, input().rstrip().split())
    def lmi(): return list(map(int, input().rstrip().split()))
    def li():  return list(input().rstrip())
    
    
    n, k = mi()
    v = lmi()
    
    
    ans = -inf
    k = min(2*n, k)
    for i in range(k+1):    
        for get_num in range(math.ceil(i/2), min(i+1, n+1)):    
            return_num = i - get_num
            
            for from_left in range(get_num+1):    
                from_right = get_num - from_left
                
                if from_right == 0:
                    L = v[:from_left]
                else:
                    L = v[:from_left] + v[-from_right:]
                ans = max(ans, sum(sorted(L)[return_num:]))    
    print(ans)




if __name__ == "__main__":
    main()

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


ans = 0

for i in range(1, k + 1):
    if i <= n:
        for j in range(i + 1):
            l = v[:j] + v[n - i + j:]
            l.sort()
            kari = sum(l)
            for x in range(min(k - i, i)):
                if l[x] >= 0:
                    break
                kari -= l[x]
            ans = max(ans, kari)

print(ans)

Solution (Python):
mod = 10 ** 9 + 7
from collections import deque
import heapq


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


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


def solve():
    N, K = iip(False)
    V = iip(True)
    V2 = [i for i in V]
    V2.reverse()

    mm = 0
    for i in range(N+1):
        for j in range(N+1):
            if i+j > K:
                continue
            if i+j > N:
                continue

            jewels = V[:i]
            jewels.extend(V2[:j])

            zyokyo = K - (i+j)

            while zyokyo >= 1:
                zyokyo -= 1
                if not jewels:
                    break
                mj = min(jewels)
                if min(jewels) < 0:
                    jewels.remove(mj)
                else:
                    break

            mm = max(mm, sum(jewels))
    return mm




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


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


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

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


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

    l = 0
    r = len(sorted_list)

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

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

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

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


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


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

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

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        
        pass
    return ret


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


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


if __name__ == "__main__":
    main()