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


import itertools
from collections import Counter
from collections import defaultdict
import bisect

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

    ans = 0
    try_count = min(N, K)
    for a in range(try_count + 1):
        
        b = 0
        while b <= try_count - a:
            can_discard = K - a - b
            
            gets = D[:a] + D[N - b:]
            
            gets.sort()

            while len(gets) > 0 and can_discard > 0:
                if gets[0] < 0:
                    gets.pop(0)
                    can_discard -= 1
                else:
                    break

            
            ans = max(ans, sum(gets))
            b += 1

    print(ans)


if __name__ == '__main__':
    main()

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

take_count = min(N,K)

ans = -1 * 10**8
for i in range(1,take_count+1):
    drop_num = K-i 
    
    for li in range(i+1):
        take_left = V[:li]
        
        for ri in range(i+1-li):
            take = take_left
            take_right = []
            if ri>0:
                take_right =  V[-ri:]
            take = take_left + take_right
            take = sorted(take)
            
            for di in range(min(drop_num, len(take))):
                if take[di] < 0:
                    take[di] = 0
            ans = max(ans, sum(take))
            
print(ans)

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

def solve(x, y):
    S = []
    r = 0
    for i in range(x):
        S.append(V[i])
        r += V[i]
    for i in range(N-1, N-y-1, -1):
        S.append(V[i])
        r += V[i]
    S.sort()
    for i in range(min(K-x-y, x+y)):
        if S[i] >= 0:
            break
        r -= S[i]
    return r

ans = 0
for i in range(K+1):
    for j in range(min(K-i+1, N-i+1)):
        ans = max(ans, solve(i, j))

print(ans)

Solution (Python):
def spaceinput():
    return list(map(int,input().split(" ")))

def gsum(l,r):
    return sum(V[l:(r)])
N,K=spaceinput()
V=spaceinput()

v_total=sum(V)
res=0
for nl in range(N):
    for nr in range(N-nl+1):
        if nl+nr>K:
            break
        l=nl
        r=N-nr-1
        if nl>0:
            temoto=V[:l]
        else:
            temoto=[]
        
        if nr>0:
            temoto.extend(V[(r+1):])            
        temoto=sorted(temoto)
        
        tmp=sum(temoto)
        
        for ss in range(K-len(temoto)):
            
            if ss>len(temoto)-1:
                break
            if temoto[ss]<0:
                tmp-=temoto[ss]
            else:
                break

        if tmp>res:
            res=tmp
            
            
            
        

print(res)

Solution (Python):
from sys import stdin
import math
import fractions
from collections import deque
import itertools

INF = 10 ** 10

N, K = [int(x) for x in stdin.readline().rstrip().split()]
V = list(map(int,stdin.readline().rstrip().split()))

getV_num = min(N, K)

ans = 0

for i in range(getV_num+1):
    toru = i
    sute = K-i

    
    
    
    for j in range(toru+1):
        leftn = j
        rightn = (toru - j)

        data = []


        for k in range(leftn):
            data.append(V[k])

        for k in range(rightn):
            data.append(V[N-1-k])

        data.sort()
        for _ in range(sute):
            if data:
                if data[0] < 0:
                    del data[0]
                else:
                    break
            else:
                break

        ans = max(ans, sum(data))

print(ans)

Solution (Python):
from heapq import heappush, heappop, heapify

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










S = 0
for take in range(min(N, K) + 1):
    for takeL in range(take + 1):
        for takeR in range(take - takeL + 1):
            hand = []
            for i in range(takeL):
                heappush(hand, V[i])
            for i in range(takeR):
                if N - i - 1 < takeL:
                    break
                heappush(hand, V[N- i - 1])
            S = max(sum(hand), S)
            for _ in range(K - take):
                if not hand or hand[0] >= 0:
                    break
                heappop(hand)
                S = max(sum(hand), S)
print(S)

Solution (Python):
import sys,collections as cl,bisect as bs,heapq as hq
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l():
	return list(map(int,input().split()))
def uy():
	return map(int,input().split())
def s(x):
	a = []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa == x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x):
	return " ".join(map(str,x))

n,m = uy()

a = l()

su = 0
for i in range(n+1):
	ll = max(i,n-(m - i))
	if ll == i:
		lll = abs(i-n-(m - i))
	else:
		lll = 0

	for j in range(ll,n+1):
		q = []
		co = 0
		p = a[:i]
		pp = a[j:]
		for k in range(len(p)):
			if p[k] < 0:
				hq.heappush(q,p[k])
		for k in range(len(pp)):
			if pp[k] < 0:
				hq.heappush(q,pp[k])
		co += sum(p)
		co += sum(pp)
		q.sort()
		for k in range(min(len(q),j-ll+lll)):
			co += abs(hq.heappop(q))
		su = max(su,co)
print(su)

Solution (Python):
n, k = [int(i) for i in input().split(" ")]
v = [int(i) for i in input().split(" ")]
mx = 0

def s(l, r):
    global mx
    d = k - l - r
    m = []
    for i in range(l):
        m.append(v[i])
    for i in range(1, r + 1):
        m.append(v[-i])
    m = sorted(m)
    ss = sum(m)
    for i in range(d):
        if i < len(m) and m[i] < 0:
            ss -= m[i]
    if ss > mx:
        mx = ss

for l in range(min(n, k) + 1):
    for r in range(min(n, k) - l + 1):
        s(l, r)

print(mx)

Solution (Python):
N, K = [int(_) for _ in input().split()]
V = [int(_) for _ in input().split()]

max_log = []

for total_take in range(min(N, K) + 1):
    for left_take in range(total_take + 1):
        right_take = total_take - left_take
        taken_set = V[:left_take] + (V[-right_take:] if right_take != 0 else [])
        taken_set.sort(reverse=True)


        if taken_set == []:
            continue
        else:
            removal = min(K - total_take, len(taken_set))
            for _ in range(removal):
                if taken_set[-1] < 0:
                    taken_set.pop()
                    if taken_set == []:break
                else:
                    break

        max_log.append(sum(taken_set))

print(max(max_log))

Solution (Python):

import sys
INF = float("inf")
from collections import deque
import heapq


def argmost(a, comp, ini):
    m, n = ini, -1
    for i, v in enumerate(a):
        if comp(m, v):
            m, n = v, i
    return m, n


def solve(N: int, K: int, V: "List[int]"):
    M = min(N, K)
    m = -INF
    for A in range(M+1):
        for B in range(M-A+1):
            jueries = V[:A] + V[N-B:]
            
            heapq.heapify(jueries)
            for i in range(K-A-B):
                if len(jueries) > 0:
                    sute = heapq.heappop(jueries)
                    if sute >= 0:
                        heapq.heappush(jueries, sute)
                        break
            s = sum(jueries)
            
            if m < s:
                m = s
    print(m)
    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):

from collections import deque
N, K = map(int, input().split())
V = [int(i) for i in input().split()]
q = deque(V)
l = []
cnt = 0
flag = True
ans = 0
for a in range(K+1):
    for b in range(K+1-a):
        max_ = 0
        q.clear()
        q = deque(V)
        flag = True
        cnt = 0
        l = []
        for _ in range(a):
            if len(q) == 0:
                flag = False
            else:
                l.append(q.popleft())
        if flag:
            for _ in range(b):
                if len(q) == 0:
                    flag = False
                else:
                    l.append(q.pop())
        else:
            continue
        if flag:
            for x in sorted(l):
                cnt += 1
                if x < 0 and cnt <= K-a-b:
                    pass
                else:
                    max_ += x
        else:
            continue
        if max_ > ans:
            ans = max_

print(ans)

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

results = []
for backn in range(k + 1):
    at = k - backn

    t = min(n, at)
    for i in range(0, t + 1):
        for shift in range(i + 1):
            p = v[:i - shift] + v[n - shift:]
            p.sort()
            value = sum(p[backn:])
            results.append(value)
print(max(results))

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

M = min(N, K)
ma = 0
for l in range(M + 1):
    for r in range(M - l + 1):
        G = V[:l] + V[N - r:]
        G.sort()
        for i in range(K - l - r + 1):
            ma = max(ma, sum(G[i:]))
print(ma)

Solution (Python):







import math, itertools, operator
from math import *
from math import factorial as fact
from operator import itemgetter, attrgetter
from itertools import permutations, combinations
from functools import reduce


from fractions import gcd

inf = float('inf')

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

def perm(a, b):
    import scipy.special
    return scipy.special.perm(a, b, exact = True)

def comb(a, b):
    import scipy.special
    return scipy.special.comb(a, b, exact = True)

def dfact(n):
    import scipy.special
    return scipy.special.factorial2(n, exact = True)

def prod(l):
    return reduce(operator.mul, l)

def input_ints(inp = input, sep = ' ', conv = int):
    return list(map(conv, inp().split(sep = sep)))



N, K = input_ints()
V = input_ints()

cnt = -inf
for LR in range(min(N,K)+1):
    disp = K - LR
    for L in range(LR+1):
        R = LR - L
        left = V[:L]
        right = V[-R:] if R > 0 else []
        s = sum(left) + sum(right)
        both = sorted(list(filter(lambda x: x < 0, left + right)))
        s -= sum(both[:disp])
        cnt = max(cnt, s)
print(cnt)

Solution (Python):
n,k,*v=map(int,open(0).read().split())
m=0
r=range
for i in r(n+1):
 for j in r(min(k-i+1,n-i+1)):
  t=sorted(v[:i]+v[-j:]*(j>0))[::-1];c=k-i-j
  while t and c and t[-1]<0:t.pop();c-=1
  m=max(m,sum(t))
print(m)

Solution (Python):
n,k=map(int,input().split())
v=list(map(int,input().split()))
ans=[]
for lhs in range(k+1):
    for rhs in range(k-lhs+1):
        if lhs+rhs<=n:
            array=v[:lhs]+v[n-rhs:]
        else:
            array=v[:]
        
        for i in range(k+1-lhs-rhs):
            array.sort()
            ans.append(sum(array[i:]))

print(max(ans))

Solution (Python):

from collections import deque

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

mn = min(N,K)   
ans = 0
for a in range(mn+1):
    for b in range(mn+1-a):
        que = deque(V)
        have = []
        for i in range(a):  
            have.append(que.popleft())
        for i in range(b):  
            have.append(que.pop())
        have.sort() 
        c = K - a - b   
        neg = [v for v in have if v < 0]
        if len(neg) < c:
            ans = max(ans, sum(have[len(neg):]))
        else:
            ans = max(ans, sum(have[c:]))

print(ans)

Solution (Python):
from bisect import bisect_left

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

ans = 0
for i in range(0, k + 1):
    for j in range(0, min(k, n) - i + 1):
        tmp = v[:i] + (v[-j:] if j else [])
        tmp.sort()
        idx = min(k - i - j, bisect_left(tmp, 0))
        ans = max(ans, sum(tmp[idx:]))

print(ans)

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

R = min(N, K)
l = []
ans = 0
for a in range(R + 1):
  for b in range(R + 1 - a):
    l = V[:a] + V[N - b:]
    l.sort()
    for i in range(K - a - b + 1):
      ans = max(ans, sum(l[i:]))
print(max(ans, 0))

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, log2
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N, K = MAP()
V = LIST()
R = min(N, K)

max_ = 0
for A in range(R+1):
	for B in range(R+1):
		if A+B > R:
			continue
		if B == 0:
			lis = V[:A]
		else:
			lis = V[:A] +  V[-B:]
		
		
		lis.sort()
		for i in range(K-(A+B)):
			if lis and lis[0] < 0:
				lis.pop(0)
		tmp = sum(lis)
		max_ = max(max_, tmp)
print(max_)

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

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

I = []

for i in range(min(n, k)+1):
    for j in range(min(n, k)-i+1):
        I.append([i, j])

Vr = V[::-1]

maxi = 0

for l in I:
    H = V[0:l[0]] + Vr[0:l[1]]
    H.sort()
    t = min(len(H), k - len(H))
    t = max(0, t)
    minus = sum(s < 0 for s in H)
    score = sum(H[min(minus, t):])
    maxi = max(maxi, score)

print(maxi)

Solution (Python):
def solve():
    A, K = map(int, input().split())
    V = list(map(int, input().split()))
    ans = 0
    for left in range(min(K, A) + 1):
        for right in range(min(K, A) - left + 1):
            S = [0] + V[:left] + V[A - right:]
            S.sort()
            drop, rest = 0, K - (left + right)
            while drop < rest and S[drop] < 0: drop += 1
            ans = max(ans, sum(S) - sum(S[:drop]))
    return ans

print(solve())

Solution (Python):
import sys
sys.setrecursionlimit(100000)

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


ans = 0
for i in range(K+1):
  hand = V[:i]
  for j in range(K-i+1):
    if j != 0:
      x = hand + V[max(N-j, i):]
    else:
      x = hand
    rest = K - i - j
    summ = sum(v for i, v in enumerate(sorted(x)) if i >= rest or v > 0)
    ans = max(ans, summ)
    
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 <= min(N,K):
            S = max(0,K-(L+R))

            A = sorted(V[:L]+V[N-R:])
            for k in range(len(A)):
                if A[k] < 0 and S > 0:
                    A[k] = 0
                    S -= 1
            ans = max(ans,sum(A))
print(ans)

Solution (Python):
N,K=map(int, input().split())
V=list(map(int, input().split()))
ans=0
from heapq import heapify,heappop
for j in range(1,min(N,K)+1):
    for k in range(j+1):
        x=V[:k]+V[N-j+k:]
        heapify(x)
        b=K-j
        while len(x)>0 and x[0]<0 and b>0:
            heappop(x)
            b-=1
        ans=max(ans,sum(x))
print(ans)

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

for i in range(1,N+1):
    if i>K:
        break
    for r in range(i+1):

        l=i-r
        a=V[:r]
        b=V[N-l:]
        f=max(0,K-i)
        c=a+b
        c.sort()
        k=0
        t=0
        for j in c:
            if t<f and j<0:
                t+=1
                continue
            k+=j
        ans=max(ans,k)
print(ans)

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


ans = 0
for i in range(K):
    
    if K-i >= N:
        pick = q
        pick = sorted(pick)
        for m in range(i+1):
            ans = max(sum(pick[m:]),ans)        
    else:
        pick = q[:K-i]
        pick = sorted(pick)
        ans = max(sum(pick[i:]),ans)
        for j in range(min(N,K-i)):
            pick = []
            pick = q[:j]+q[-(K-i-j):]
            pick = sorted(pick)
            for m in range(i+1):
                ans = max(sum(pick[m:]),ans)        
print(ans)

Solution (Python):
n, k = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for pull in range(k + 1):
    for back in range(k):
        if pull + back != k:
            continue
        for l in range(pull+1):
            r = pull - l
            if r > 0:
                hand = V[:l] + V[-r:]
            else:
                hand = V[:l]
            if pull >= n:
                hand = V
            hand = sorted(hand, reverse=True)
            for _ in range(back):
                if len(hand) == 0:
                    break
                if hand[-1] < 0:
                    hand.pop()
                else:
                    break
            ans = max(ans, sum(hand))
print(ans)

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

R = min(N, K)
ans = 0
for a in range(R+1):
    for b in range(R-a+1):
        items = V[:a] + V[N-b:]
        items.sort()
        for c in range(K-a-b+1):
            ans = max(ans, sum(items[c:]))
print(ans)

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

for cd in range(K):
    ab = min(N, K-cd)
    for left_ab in range(ab+1):
        right_ab = ab - left_ab
        if right_ab > 0:
            pick = V[:left_ab] + V[-right_ab:]
        else:
            pick = V[:left_ab]
        pick.sort()
        neg = 0
        while neg < len(pick):
            if pick[neg]<0:
                neg+=1
                continue
            else:
                break
        v = sum(pick[min(neg,cd):])
        value = max(value,v)
        
print(value)

Solution (Python):
import sys
from heapq import heappop, heappush

def main():
    input = sys.stdin.readline
    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, K) - left + 1):
            heap = []
            for v in V[:left]:
                heappush(heap, v)

            for v in V[N - right:]:
                heappush(heap, v)

            cnt = left + right
            while cnt < K and len(heap) > 0:
                v = heappop(heap)
                if v > 0:
                    heappush(heap, v)
                    break

                cnt += 1

            ans = max(ans, sum(heap))

    return ans


if __name__ == '__main__':
    print(main())

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

s = 0
for i in range(min(N, K) + 1):
  
  res = K - i
  
  
  for j in range(i + 1):
    
    k = i - j
    
    
    Q = sorted(V[:j] + V[N - k:])
    
    
    minus = sum([q < 0 for q in Q])
    
    
    score = sum(Q[min(minus, res):])
    
    
    s = max(s, score)

print(s)

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 - a, k - a) + 1):
        v_use = v[:a] + v[-b:] if b >= 1 else v[:a]
        t = k - a - b
        s = 0
        for j in sorted(v_use):
            if j < 0 and t > 0:
                s += -j
                t -= 1
        ans = max(ans, sum(v_use) + s)

print(ans)

Solution (Python):
N, K = map(int, input().split())
V = list(map(int, input().split()))
M = min(N, K)
ans = 0
for p in range(M+1):
  for q in range(M-p+1):
    left = []
    right = []
    if p > 0:
      left = V[:p]
    if q > 0:
      right = V[-q:]
    have = sorted((left+right).copy())
    if len(have) > 0:
      for i in range(min(len(have),K-p-q+1)):
        if have[i] > 0:
          break
      ans = max(sum(have[i:]),ans)
print(ans)

Solution (Python):
n,k = map(int,input().split())
v = list(map(int,input().split()))
ans = 0
for a in range(n):
    for b in range(a,n+1):
        c = 0
        if a+n-b <= k:
            p = k-(a+n-b)
            s = v[:a]+v[b:]
            s.sort()
            for t in s:
                if p >= 1 and t < 0:
                    p -= 1
                else:
                    c += t

        ans = max(c,ans)

print(ans)

Solution (Python):


import sys
input = sys.stdin.readline


N, K = map(int, input().split())
D = [int(x) for x in input().split()]


ans = 0
for l in range(N + 1):
    if l > K:
        break

    for r in range(N - l + 1):
        if l + r > K:
            break

        value_list = D[0 : l] + D[N - r : N]
        value_list.sort()
        
        for i in range(K - (l + r) + 1):
            ans = max(ans, sum(value_list[i:]))
        
print(ans)

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

results = []
for a in range(n + 1):
    for b in range(min(n - a, k - a) + 1):
        p = v[:a] + v[n - b:]
        p.sort()
        for i in range(k - a - b + 1):
            results.append(sum(p[i:]))
print(max(results))

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

ans = 0
if n == 1:
    ans = max(0, v[0])
else:
    ans = 0 if k < n else sum(v)
    for i in range(min(k + 1, n)):
        for j in range(i + 1):
            t = v[:j]
            if j != i:
                t += v[j - i:]
            t.sort()
            for p in range(k - i):
                if len(t) > 0 and t[0] < 0:
                    t.pop(0)
                else:
                    break
            if len(t) == 0:
                t = [0]
            ans = max(ans, sum(t))
print(ans)

Solution (Python):



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

sum_max = 0
for t in range(min(2*n+1, k+1)):
  if t > 0:
    for put in range(t//2 + 1):
      pick = t - put
      for left in range(min(pick+1,n+1)):
        right= min(pick,n) - left
        if left!=0:
          vs=v[0:left]
        else:
          vs=[]
        if right!=0:
          vs.extend(v[-right:])
        vs.sort()
        for i in range(put):
          if vs !=[]:
            if vs[0] < 0:
              del vs[0]
            else:
              break
          else:
            break

        sum_max = max(sum_max, sum(vs))
print(sum_max)

Solution (Python):
import heapq


def main():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    if N <= K:
        V.sort()
        total = sum(V)
        ans = max(total, 0)
        for i in range(min(K-N, N)):
            total -= V[i]
            ans = max(ans, total)
        print(ans)
    else:
        left = [0] * (K+1)
        right = [0] * (K+1)
        for i in range(K, 0, -1):
            lv = V[:i]
            rv = V[-i:]
            left[i] = sum(lv)
            right[i] = sum(rv)
            lheap = list(lv)
            rheap = list(rv)
            heapq.heapify(lheap)
            heapq.heapify(rheap)
            lmsum = 0
            rmsum = 0
            for j in range(1, i):
                if i+j > K:
                    continue
                lmsum += heapq.heappop(lheap)
                left[i+j] = max(left[i+j], left[i] - lmsum)
                rmsum += heapq.heappop(rheap)
                right[i+j] = max(right[i+j], right[i] - rmsum)
        for i in range(1, K+1):
            left[i] = max(left[i], left[i-1])
            right[i] = max(right[i], right[i-1])
        ans = 0
        for i in range(K+1):
            ans = max(max(left[i], 0) + max(right[K-i], 0), ans)
        print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
a,k=map(int,input().split())
L=list(map(int,input().split()))
ans=0
 
for i in range(min(k,a)+1):
  for j in range(min(k,a)-i+1):
    S=[0]+L[:i]+L[a-j:]
    S.sort()
    x=0
    while x < k-(j+i):
      if S[x]>=0:
        break
      x+=1
    ans=max(ans,sum(S)-sum(S[:x]))
    
print(ans)

Solution (Python):
import math, string, itertools, fractions, heapq, collections, re, array, bisect, copy, functools, random
import sys
from collections import deque, defaultdict, Counter; from heapq import heappush, heappop
from itertools import permutations, combinations, product, accumulate, groupby
from bisect import bisect_left, bisect_right, insort_left, insort_right
from operator import itemgetter as ig
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20; INF = float("INF"); ans = 0; tmp = 0; ansli = []; tmpli = []; candili = []
eps = 1.0 / 10 ** 10; mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]; ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)]; ddn9 = ddn + [(0, 0)]
"""for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:"""
def wi(): return list(map(int, sys.stdin.readline().split()))
def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def ws(): return sys.stdin.readline().split()
def i(): return int(sys.stdin.readline())
def s(): return input()
def hi(n): return [i() for _ in range(n)]
def hs(n): return [s() for _ in range(n)]
def mi(n): return [wi() for _ in range(n)]
def mip(n): return [wip() for _ in range(n)]
def ms(n): return [ws() for _ in range(n)]

n, k = wi()
v = wi()
v = deque(v)
pq = []
po = 0
cnt = 0
qwerty = min(n + 1, k + 1)
for i in range(qwerty):
    if i != 0:
        heappush(pq, v[i - 1])
    for j in range(qwerty - i):
        if j != 0:
            heappush(pq, v[-j])
        while k - i - j - cnt > 0:
            if pq != []:
                po = 0
                po = heappop(pq)
                if po < 0:
                    cnt += 1
                    tmpli.append(po)
                else:
                    heappush(pq, po)
                    cnt = 0
                    break
            else:
                break
        cnt = 0
        ans = max(ans, sum(pq))
        for bb in tmpli:
            heappush(pq, bb)
        tmpli = []
    pq = []
    for g in range(i + 1):
        if g != 0:
            heappush(pq, v[g - 1])

print(ans)

Solution (Python):
import heapq


def main():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    if N <= K:
        V.sort()
        total = sum(V)
        ans = max(total, 0)
        for i in range(min(K-N, N)):
            total -= V[i]
            ans = max(ans, total)
        print(ans)
    else:
        left = [0] * (K+1)
        right = [0] * (K+1)
        for i in range(K, 0, -1):
            lv = V[:i]
            rv = V[-i:]
            left[i] = sum(lv)
            right[i] = sum(rv)
            lheap = list(lv)
            rheap = list(rv)
            heapq.heapify(lheap)
            heapq.heapify(rheap)
            lmsum = 0
            rmsum = 0
            for j in range(1, i):
                if i+j > K:
                    continue
                lmsum += heapq.heappop(lheap)
                left[i+j] = max(left[i+j], left[i] - lmsum)
                rmsum += heapq.heappop(rheap)
                right[i+j] = max(right[i+j], right[i] - rmsum)
        for i in range(1, K):
            left[i] = max(left[i], left[i-1])
            right[i] = max(right[i], right[i-1])
        ans = 0
        for i in range(K+1):
            ans = max(max(left[i], 0) + max(right[K-i], 0), ans)
        print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
n,k=map(int,input().split())
d=list(map(int,input().split()))
ans=0
for l in range(min(n,k)+1):
    for r in range(min(n-l,k-l)+1):
        tl=d[:l]+d[-r:] if r>0 else d[:l]
        tk=k-l-r
        s=0
        for t in sorted(tl):
            if t<0 and tk>0:
                s+=-t
                tk-=1
            ans=max(ans,sum(tl)+s)
print(ans)

Solution (Python):
import math, string, itertools, fractions, heapq, collections, re, array, bisect, copy, functools, random
import sys
from collections import deque, defaultdict, Counter; from heapq import heappush, heappop
from itertools import permutations, combinations, product, accumulate, groupby
from bisect import bisect_left, bisect_right, insort_left, insort_right
from operator import itemgetter as ig
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20; INF = float("INF"); ans = 0; tmp = 0; ansli = []; tmpli = []; candili = []
eps = 1.0 / 10 ** 10; mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]; ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)]; ddn9 = ddn + [(0, 0)]
"""for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:"""
def wi(): return list(map(int, sys.stdin.readline().split()))
def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def ws(): return sys.stdin.readline().split()
def i(): return int(sys.stdin.readline())
def s(): return input()
def hi(n): return [i() for _ in range(n)]
def hs(n): return [s() for _ in range(n)]
def mi(n): return [wi() for _ in range(n)]
def mip(n): return [wip() for _ in range(n)]
def ms(n): return [ws() for _ in range(n)]

n, k = wi()
v = wi()
v = deque(v)
pq = []
po = 0
cnt = 0
qwerty = min(n + 1, k + 1)
for i in range(qwerty):
    if i != 0:
        heappush(pq, v[i - 1])
    for j in range(qwerty - i):
        if j != 0:
            heappush(pq, v[-j])
        while k - i - j - cnt > 0:
            if pq != []:
                po = 0
                po = heappop(pq)
                if po < 0:
                    cnt += 1
                    tmpli.append(po)
                else:
                    heappush(pq, po)
                    cnt = 0
                    break
            else:
                break
        cnt = 0
        ans = max(ans, sum(pq))
        for bb in tmpli:
            heappush(pq, bb)
        tmpli = []
    pq = []
    for g in range(i + 1):
        if g != 0:
            heappush(pq, v[g - 1])

print(ans)