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 = list(map(int, input().split()))

ans = 0

for left in range(k+1):
    for right in range(k - left + 1):
        if left + right > n:
            continue
        rock = v[:left] + v[::-1][:right]
        rock.sort()
        rem = k - left - right
        while rem > 0 and len(rock) > 0 and rock[0] < 0:
            rock = rock[1:]
            rem -= 1
        ans = max(ans, sum(rock))

print(ans)

Solution (Python):
import numpy as np
from collections import defaultdict
from functools import reduce



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

class Interval():
    def __init__(self, li):
        self.li = li
        self.n = len(li)
        self.sum_li = [li[0]]
        for i in range(1, self.n):
            self.sum_li.append(self.sum_li[i-1] + li[i])

    def sum(self, a, b=None):
        if b is None:
            return self.sum(0, a)

        res = self.sum_li[min(self.n-1, b-1)]
        if a > 0:
            res -= self.sum_li[a-1]
        return res


res = 0
for k in range(K+1):
    for l in range(k+1):
        pos = 0
        neg = []
        for i in range(min(l, N)):
            if i >= N:
                break
            if V[i] >= 0:
                pos += V[i]
            else:
                neg.append(V[i])

        for i in range(min(k-l, N-l)):
            if i >= N:
                break
            v = V[N-i-1]
            if v >= 0:
                pos += v
            else:
                neg.append(v)

        

        for i, v in enumerate(sorted(neg)):
            if i < K-k:
                continue
            pos += v
        res = max(res, pos)

print(res)

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-i+1):
        if i+j>k:
            continue
        tmp=V[:i]+V[n-j:]
        tmp.sort(reverse=True)
        for l in range(k-i-j):
            if tmp and tmp[-1]<0:
                tmp.pop()
            else:
                break
        ans=max(ans,sum(tmp))
print(ans)

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

p = min(n, k)

res = 0

for i in range(p, -1, -1):
        
        for l in range(i + 1):
                r = i - l
                
                q = []
                for w in range(l):
                        q.append(v[w])
                for w in range(n - r, n):
                        q.append(v[w])
                q = sorted(q)
                ans = sum(q)
                tmp = ans
                for w in range(min(k - i, len(q))):
                        tmp -= q[w]
                        ans = max(ans, tmp)
                res = max(res, ans)



print(res)

Solution (Python):
N, K = map(int, input().split())
v = list(map(int, input().split()))
res = []
for i in range(K+1):
    for j in range(K-i+1):

        _v = v[::]
        stock = []
        stock.extend(_v[:i])
        _v = _v[i:]
        _v.reverse()
        stock.extend(_v[:j])
        stock.sort()
        for k in range(K-i-j+1):
            res.append(sum(stock[k:]))
print(max(res))

Solution (Python):
import heapq

n, K = map(int, input().split())
v = list(map(int, input().split()))
cum = [0] * (n+1)
for i in range(n):
    cum[i+1] += cum[i] + v[i]

ans = 0
for k in range(K+1):
    for i in range(k+1):
        if i > n:
            break
        j = k - i
        if j > i:
            continue
        for l in range(i+1):
            r = i - l
            score = 0
            hq = []
            for li in range(l):
                score += v[li]
                heapq.heappush(hq, v[li])
            for ri in range(r):
                ri = n - 1 - ri
                score += v[ri]
                heapq.heappush(hq, v[ri])
            for t in range(j):
                a = heapq.heappop(hq)
                score -= a
            ans = max(ans, score)

print(ans)

Solution (Python):
import bisect
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-i+1):
        if k>=i+j:
            houseki=[]
            houseki+=v[:i]
            houseki+=v[n-j:]
            houseki=sorted(houseki)
            p=k-i-j
            p=(min(bisect.bisect_left(houseki, 0), p))
            ans=max(ans, sum(houseki[p:]))
print(ans)

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

ma = 0
for i in range(K):
    P = K - i
    for p in range(P + 1):
        q1 = []
        q2 = []
        s = 0
        for j in range(min(N, p)):
            if V[j] >= 0:
                s += V[j]
            else:
                q1.append(V[j])
        if len(q1) == p:
            q1 = []
        for j in range(N - 1, max(p - 1, N - (P - p) - 1), -1):
            if V[j] >= 0:
                s += V[j]
            else:
                q2.append(V[j])
        if len(q2) == P - p:
            q2 = []

        q = sorted(q1 + q2)
        if len(q) < i:
            t = 0
        else:
            t = sum(q[i:])
        ma = max(s + t, ma)

print(ma)

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

maxv = 0
for t in range(k+1):
    mr = k - t  

    if t >= n:
        vss = sorted(vs)
        for r in range(min(t, mr)+1):
            maxv = max(maxv, sum(vss[r:]))
    else:
        for il in range(t+1):
            ir = t - il
            vss = vs[:il] if ir == 0 else vs[:il] + vs[-ir:]
            vss = sorted(vss)
            for r in range(min(t, mr)+1):
                maxv = max(maxv, sum(vss[r:]))

print(maxv)

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

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

max_have = 0

for i in range(k + 1):
    if i > n:
        break

    left = v[:i]

    rest = v[i:][::-1]
    rest_n = n - i

    for j in range(k - i + 1):
        if j > rest_n:
            break

        right = rest[:j]

        have = left + right
        have.sort(reverse=True)

        for x in range(k - i - j):
            if not have:
                break

            if have[-1] < 0:
                have.pop()

        if sum(have) > max_have:
            max_have = sum(have)

print(max_have)

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+1, len(v)+1)):
    
    for j in range(i):
        ans = []
        q = deque(v)
        for _ in range(j):
            ans.append(q.pop())
        for _ in range(i-j):
            ans.append(q.popleft())
        ans = sorted(ans)
        pos = 0
        for t in range(min(len(ans),k-i)):
            if ans[t] <= 0:
                pos = t + 1
            else:
                break      
        res = max(sum(ans[pos:]), res)
  
print(res)

Solution (Python):
N, K = map(int, input().split(" "))
Values = list(map(int, input().split(" ")))
maxS = 0

for garbage in range((K+1)//2):
    for i in range(K-garbage+1):
        catch = []
        if K-garbage >= N:
            catch = Values
        else:
            catch = Values[0:K-garbage-i] + Values[N-i:N]
        S = sum(catch)
        catch = sorted(catch)
        tmp = garbage
        for c in catch:
            if tmp == 0 or c >= 0:
                break
            S -= c
            tmp -= 1
        maxS = max(S, maxS)
print(maxS)

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

values = []

if k > 1:
  for num_enqueue in range(k // 2):
    for num_dequeue in range(k-num_enqueue+1):
      for num_dequeue_left in range(num_dequeue+1):
        num_dequeue_right = num_dequeue - num_dequeue_left
        if num_dequeue >= n:
          dequeued = vs[:]
        else:
          dequeued = vs[:num_dequeue_left] + ([] if num_dequeue_right == 0 else vs[-num_dequeue_right:])
        dequeued_pos = [v for v in dequeued if v >= 0]
        dequeued_neg = sorted([v for v in dequeued if v < 0], reverse=True)

        for _ in range(num_enqueue):
          if dequeued_neg:
            dequeued_neg.pop()
        value = sum(dequeued_pos) + sum(dequeued_neg)
        
        values.append(value)
  print(max(values))
else:
  print(max(vs[0], vs[-1], 0))

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

max_sum_v = -1 * 10 ** 10

for n_l in range(n):
	sum_v = sum([x for x in vs[:n_l] if x >= 0])
	neg_vs = [x for x in vs[:n_l] if x < 0]
	for n_r in range(n_l, n + 1):
		if n_l + (n - n_r) > k:
			continue
		sum_v2 = sum_v + sum([x for x in vs[n_r:] if x >= 0])
		neg_vs2 = neg_vs + [x for x in vs[n_r:] if x < 0]
		neg_vs2.sort()
		rest = k - n_l - (n - n_r)
		if len(neg_vs2) > rest:
			sum_v2 += sum(neg_vs2[rest:])

		

		max_sum_v = max(max_sum_v, sum_v2)

print(max_sum_v)

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

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

ans = -99999999999
for modosi in range(K + 1):
	for tridashi in range(K + 1 - modosi):
		for tridashi_pos_r in range(tridashi + 1):
			tridashi_pos_l = tridashi - tridashi_pos_r
			if tridashi_pos_l + tridashi_pos_r > N:
				tridashi_pos_r = N
				tridashi_pos_l = 0
			
			use_vals = list(vals[:tridashi_pos_r])
			if tridashi_pos_l != 0:
				use_vals += list(vals[-tridashi_pos_l:])
			use_vals.sort()
			minus_idx = min(len([a for a in use_vals if a < 0]),modosi)
			
			val = sum(use_vals[minus_idx:])
			if val > ans:
				ans = val
print(ans)

Solution (Python):
n,k=map(int,input().split())
l=[int(i) for i in input().split()]
if k>=n:
    ans=max(sum(l),0)
else:
    ans=0
for i in range(n):
    for j in range(n-i):
        if j==0:
            ll=l[:i]
        else:
            ll=l[:i]+l[-j:]
        if(len(ll)>k or len(ll)==0):
            continue
        ll.sort()
        x=sum(ll)
        for jj in range(min(k-len(ll),len(ll))):
            if ll[jj]<0:
                x-=ll[jj]
            else:
                break
        ans=max(ans,x)
print(ans)

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

max_value = 0
r_nega, r_posi = [],0
for n_take_r in range(min(K+1, N+1)):    
    if n_take_r >= 1:
        v_take = V[N-n_take_r]
        if v_take < 0: r_nega.append(v_take)
        else: r_posi += v_take
        
    l_nega, l_posi = [],0
    for n_take_l in range(min(K+1, N+1)-n_take_r):
        if n_take_l >= 1:
            v_take = V[n_take_l-1]
            if v_take < 0: l_nega.append(v_take)
            else: l_posi += v_take

        n_remove = K - n_take_r - n_take_l
        value = r_posi + l_posi + sum(sorted(r_nega+l_nega)[n_remove:])
        max_value = max(max_value, value)

print(max_value)

Solution (Python):
def getN():
    return int(input())

def getMN():
    return list(map(int, input().split()))

def getlist():
    return list(map(int, input().split()))

n, k = getlist()
gem = getlist()
ans = 0
tansaku = min(n, k)
for i in range(tansaku):
    for l in range(tansaku+1):
        for r in range(tansaku-l+1):
            gets = gem[:l] + gem[n-r:]
            gets.sort()
            ret = k-l-r
            tmp = sum(gets)
            
            for g in gets:
                if ret > 0 and g <= 0:
                    tmp -= g
                    ret -= 1
                else:
                    break
            
            if ans < tmp:
                ans = tmp

if k < n:
    res = k-n
    tmp = sum(gets)
    gets = sorted(gets)
    for g in gets:
        if res > 0 and g <= 0:
            tmp -= g
            res -= 1
        else:
            break
    if ans < tmp:
        ans = tmp


print(ans)

Solution (Python):
import heapq

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

lsum = [0]
rsum = [0]
lmsum = [0]
rmsum = [0]
for i in range(N):
    lsum.append(lsum[-1]+V[i])
    rsum.append(rsum[-1]+rV[i])
    if V[i] < 0:
        lmsum.append(lmsum[-1]+V[i])
    else:
        lmsum.append(lmsum[-1])
    if rV[i] < 0:
        rmsum.append(rmsum[-1]+rV[i])
    else:
        rmsum.append(rmsum[-1])
ans = 0 
for l in range(N+1):
    for r in range(N-l+1):
        if l + r > K:
            break
        got = V[:l]+rV[:r]
        if not got:
            break
        heapq.heapify(got)
        val = sum(V[:l]+rV[:r])
        ans = max(ans, val)
        for b in range(min(K-l-r,l+r)):
            val -= heapq.heappop(got)
            ans = max(ans, val)
print(ans)

Solution (Python):
N,K = (int(x) for x in input().split())

V_arr = [int(x) for x in input().split()]

ans = 0
for l in range(K+1):
    if l > N:
        continue
    l_arr = V_arr[:l]
    for r in range(K+1-l):
        if l == 0 and r == 0:
            continue
        if l+r > N:
            continue
        r_arr = V_arr[N-r:]
        have_arr = sorted(l_arr+r_arr)
        delete_top = 0
        for d in range(K-l-r):
            if d >= l+r:
                break
            if have_arr[d] > 0:
                break
            delete_top = d+1
        ans = max(ans, sum(have_arr[delete_top:]))

print(ans)

Solution (Python):


N,K=map(int,input().split())
V=[int(i) for i in input().split()]
ans=0
for X in range(K+1):
    for Y in range(K+1-X):
        q=[]
        Z=K-X-Y
        if X+Y>N:
            continue
        tmp=0
        for i in range(X):
            tmp+=V[i]
            if V[i]<0:
                q.append(V[i])
        for i in range(N-Y,N):
            tmp+=V[i]
            if V[i]<0:
                q.append(V[i])
        q.sort()
        if len(q)<=Z:
            tmp-=sum(q)
        else:
            tmp-=sum(q[:Z])
        ans=max(tmp,ans)
print(ans)

Solution (Python):
vl,abcl = tuple(map(int,input().split()))
vs = list(map(int,input().split()))

ares = [0]
for v in vs:
  ares.append(ares[-1]+v)

bres = [0]
for v in reversed(vs):
  bres.append(bres[-1]+v)


best = 0
for al in range(0,min(vl+1,abcl+1)):
  for bl in range(0,min(vl+1-al,abcl+1-al)):
    re = ares[al]+bres[bl]
    got = vs[:al]+vs[vl-bl:]
    got.sort()
    cl = 0
    while cl < al+bl and cl < abcl-al-bl and got[cl]<0:
      cl += 1
    re -= sum(got[:cl])
    

    if re>best:
      best=re

print(best)

Solution (Python):
from collections import defaultdict
N,K=map(int,input().split())
V=list(map(int,input().split()))
left=[defaultdict(int) for i in range(N+1)]
left[0][0]=0
for i in range(1,1+N):
    for j in range(i,2*i+1):
        if j==i:
            left[i][j]=left[i-1][j-1]+V[i-1]
        elif j==2*i:
            left[i][j]=left[i-1][j-2]
        else:
            left[i][j]=max(left[i-1][j-2],left[i-1][j-1]+V[i-1])
right=[defaultdict(int) for i in range(N+1)]
right[0][0]=0
for i in range(1,1+N):
    for j in range(i,2*i+1):
        if j==i:
            right[i][j]=right[i-1][j-1]+V[N-i]
        elif j==2*i:
            right[i][j]=right[i-1][j-2]
        else:
            right[i][j]=max(right[i-1][j-2],right[i-1][j-1]+V[N-i])
L=[[0]*(K+1) for i in range(N+1)]
R=[[0]*(K+1) for i in range(N+1)]

for i in range(N+1):
    L[i][0]=left[i][0]
    R[i][0]=right[i][0]
    for k in range(1,K+1):
        L[i][k]=max(L[i][k-1],left[i][k])
        R[i][k]=max(R[i][k-1],right[i][k])
ans=0
for l in range(N+1):
    for r in range(N-l+1):
        for k in range(K+1):
            ans=max(ans,L[l][k]+R[r][K-k])
print(ans)

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

ans = 0
for take in range(min(k, n)+1):
    push = k-take
    for l_take in range(take+1):
        r_take = take - l_take
        jew = v[:l_take] + v[n-r_take:]
        jew.sort()
        val = sum(jew)
        for i in range(min(push, len(jew))):
            if jew[i] < 0:
                val -= jew[i]
            else:
                break
        ans = max(ans, val)
print(ans)

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

ans = 0
for l_pop in range(K + 1):
    for r_pop in range(K + 1):
        X = []
        if (l_pop + r_pop > K) or (l_pop + r_pop > N):
            continue
        else:
            X.extend(V[:l_pop])
            X.extend(V[::-1][:r_pop])

        X.sort()
        tmp = sum(X)
        for k in range(K - l_pop - r_pop):
            if k > len(X) - 1:
                break
            else:
                if X[k] < 0:
                    tmp -= X[k]

        ans = max(ans, tmp)

print(ans)

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

    now_max = min(values) - 1
    for left_num in range(n + 1):
        for right_num in range(n - left_num + 1):
            if left_num + right_num > k:
                break
            for discard_num in range(k - left_num - right_num + 1):
                left_values = values[:left_num]
                right_values = list(reversed(values))[:right_num]
                all_values = left_values + right_values
                result = sum(sorted(all_values)[discard_num:])
                if result > now_max:
                    now_max = result
    print(now_max)


if __name__ == '__main__':
    main()

Solution (Python):



def readInt():
    return int(input())

def readList():
    return list(input().split())

def readListI():
    return list(map(int, input().split()))

def main():
    n, k = readListI()
    lv = readListI()
    ret = 0
    for l in range(min(n, k)+1):
        for r in range(min(n, k)+1-l):
            jewel = sorted(lv[:l] + lv[n-r:])
            for p in range(l+r):
                if l+r+p > k:
                    continue
                ret = max(ret, sum(jewel[p:]))
    print(ret)


if __name__ == '__main__':
    main()

Solution (Python):
from bisect import bisect_left

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

ans = -float("inf")
for i in range(1 + min(N, K)):
    for j in range(1 + min(N - i, K - i)):
        if i == j == 0:
            ans = max(ans, 0)
            continue
        remk = K - i - j
        v = D[:i] + D[N-j:]
        v.sort()
        numge0 = bisect_left(v, 0)
        ans = max(ans, sum(v[min(remk, numge0):]))

print(ans)

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

Value=list(map(int,input().strip().split(' ')))

MAX=0

def find(a,b,K,N):
    negative=[]
    sum_up=0
    for i in range(a):
        sum_up+=Value[i]
        if Value[i]<0:
            negative+=[Value[i]]
    
    for i in range(1,b+1):
        sum_up+=Value[-i]
        if Value[-i]<0:
            negative+=[Value[-i]]
    negative=sorted(negative)
    sum_up-=sum(negative[:K-a-b])
    return sum_up



for a in range(min(N,K)+1):
    for b in range(min(N,K)+1-a):
        sum_up=find(a,b,K,N)
        MAX=max(MAX,sum_up)

print(MAX)

Solution (Python):
from heapq import heappop,heappush
from copy import deepcopy
from collections import deque
N,K=map(int,input().split())
V=[int(i) for i in input().split()]
ans=0
for s in range(K+1):
    for t in range(K+1-s):
        i=s
        j=t
        U=deque(V)
        
        num=0
        H=[]
        while len(U) > 0 and i > 0:
            i -= 1
            x = U.popleft()
            heappush(H, x)
            num+=x
        while len(U) > 0 and j > 0:
            j -= 1
            x = U.pop()
            heappush(H, x)
            num+=x
        k=K-s-t
        
        while len(H)>0 and k>0:
            k-=1
            y=heappop(H)
            
            if y<=0:
                num-=y
        ans=max(num,ans)
print(ans)

Solution (Python):


from sys import stdout
from bisect import bisect_left as binl
from copy import copy, deepcopy
from collections import defaultdict
import math


mod = 1


def intin():
    input_tuple = input().split()
    if len(input_tuple) <= 1:
        return int(input_tuple[0])
    return tuple(map(int, input_tuple))


def intina():
    return [int(i) for i in input().split()]


def intinl(count):
    return [intin() for _ in range(count)]


def modadd(x, y):
    global mod
    return (x + y) % mod


def modmlt(x, y):
    global mod
    return (x * y) % mod


def lcm(x, y):
    while y != 0:
        z = x % y
        x = y
        y = z
    return x


def combination(x, y):
    assert(x >= y)

    ret = math.factorial(x)
    ret = ret // (math.factorial(x - y) * math.factorial(y))

    return ret


def get_divisors(x):
    retlist = []
    for i in range(1, int(x**0.5) + 3):
        if x % i == 0:
            retlist.append(i)
            retlist.append(x // i)
    return retlist


def get_factors(x):
    retlist = []
    for i in range(2, int(x**0.5) + 3):
        while x % i == 0:
            retlist.append(i)
            x = x // i
    retlist.append(x)
    return retlist


def make_linklist(xylist):
    linklist = {}
    for a, b in xylist:
        linklist.setdefault(a, [])
        linklist.setdefault(b, [])
        linklist[a].append(b)
        linklist[b].append(a)
    return linklist


def calc_longest_distance(linklist, v=1):
    distance_list = {}
    distance_count = 0
    distance = 0
    vlist_previous = []
    vlist = [v]
    nodecount = len(linklist)

    while distance_count < nodecount:
        vlist_next = []
        for v in vlist:
            distance_list[v] = distance
            distance_count += 1
            vlist_next.extend(linklist[v])
        distance += 1
        vlist_to_del = vlist_previous
        vlist_previous = vlist
        vlist = list(set(vlist_next) - set(vlist_to_del))

    max_distance = -1
    max_v = None
    for v, distance in distance_list.items():
        if distance > max_distance:
            max_distance = distance
            max_v = v

    return (max_distance, max_v)


def calc_tree_diameter(linklist, v=1):
    _, u = calc_longest_distance(linklist, v)
    distance, _ = calc_longest_distance(linklist, u)
    return distance


class UnionFind:

    def __init__(self, n):
        self.parent = [i for i in range(n)]

    def root(self, i):
        if self.parent[i] == i:
            return i
        self.parent[i] = self.root(self.parent[i])
        return self.parent[i]

    def unite(self, i, j):
        rooti = self.root(i)
        rootj = self.root(j)
        if rooti == rootj:
            return
        if rooti < rootj:
            self.parent[rootj] = rooti
        else:
            self.parent[rooti] = rootj

    def same(self, i, j):
        return self.root(i) == self.root(j)





def main():
    n, k = intin()
    vlist = intina()

    ans = -float('inf')

    for i in range(min(k + 1, n + 1)):
        for left in range(i + 1):
            right = i - left
            max_discard = k - i
            getlist = vlist[:left]
            getlist.extend(vlist[(n-right):])
            getlist.sort()
            idx = binl(getlist, 0)
            ans = max(ans, sum(getlist[min(max_discard, idx):]))

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
def makelist(n, m):
    return [[0 for _ in range(m)] for _ in range(n)]


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

ans = 0
for l in range(K+1):
    for r in range(K+1-l):
        if l + r > N:
            break
        L = V[:l]
        R = V[N-r:]

        hoge = L + R
        hoge.sort()
        
        
        ind = min(K - (l + r), len(hoge)) - 1
        while ind >= 0:
            if hoge[ind] < 0:
                break
            ind -= 1
        if ind >= 0:
            ans = max(ans, sum(hoge[ind+1:]))
        else:
            ans = max(ans, sum(hoge))
        
print(ans)

Solution (Python):


import sys
import math

import array
import bisect
import collections
from collections import Counter, defaultdict
import fractions
import heapq
import re

sys.setrecursionlimit(1000000)


def array2d(dim1, dim2, init=None):
    return [[init for _ in range(dim2)] for _ in range(dim1)]

def argsort(l, reverse=False):
    return sorted(range(len(l)), key=lambda i: l[i], reverse=reverse)

def argmin(l):
    return l.index(min(l))

def YESNO(ans, yes="YES", no="NO"):
    print([no, yes][ans])

II = lambda: int(input())
MI = lambda: map(int, input().split())
MIL = lambda: list(MI())
MIT = lambda: tuple(MI())
MIS = lambda: input().split()


def get(V, n):
    if n >= len(V):
        yield V
    else:
        yield V[:n]
        for i in range(1, n):
            yield V[:n-i] + V[-i:]
        yield V[-n:]


def main():
    N, K = MI()
    V = MIL()
    ans = 0

    for i in range(max(K//2, 1), K + 1):
        
        for vs in get(V, i):
            
            vs = sorted(vs)
            for j, v in enumerate(vs):
                if v >= 0: break
            ans = max(ans, sum(vs[min(K-i, j):]))
    return ans


if __name__ == "__main__":
    print(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(i, N+1):
        stone = V[:i] + V[j:]
        if len(stone) > K:
            continue
        else:
            count = K-len(stone)
            stone.sort()
            for k in range(min(count, len(stone))):
                if stone[k] < 0:
                    stone[k] = 0
                else:
                    break
            ans = max(ans, sum(stone))
print(ans)

Solution (Python):
from bisect import bisect, bisect_left
import sys

def inpl(): return list(map(int, input().split()))

N, K = inpl()
V = inpl()
ans = 0
for a in range(min(K+1, N+1)):
    for b in range(min(K-a, N-a)+1):
        U = V[:a] + V[N-b:]
        U = sorted(U)
        l = bisect_left(U, 0)
        k = K - a - b
        if k <= l:
            ans = max(ans, sum(U[k:]))
        else:
            ans = max(ans, sum(U[l:]))

print(ans)

Solution (Python):
N, K = map(int, input().split())
V = [int(a) for a in input().split()]
INF = 1<<50
ma = 0
for i in range(min(K, N)+1):
    for j in range(i+1):
        S = sorted(V[:j] + ([] if i==j else V[-(i-j):]))
        ma = max(ma, sum([max(S[t], (0 if t < K-i else -INF)) for t in range(len(S))]))
print(ma)

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

ANS=0

for i in range(min(N,K)+1):
    for j in range(min(N,K)-i+1):
        A=V[:i]
        B=V[N-j:]
        C=A+B
        
        C.sort()
        for k in range(min(K-i-j,len(C))):
            if C[k]<0:
                C[k]=0
        
        if ANS<sum(C):
            ANS=sum(C)
print(ANS)

Solution (Python):

def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(input())
def S(): return list(input())
n,k=IL()
V=IL()
ans=0

for i in range(min(k+1,n+1)):
    
    
    for j in range(i+1):
        t=0
        m=[]
        for l in range(j):
            if V[l]<0:
                m.append(V[l])
            else:
                t+=V[l]
        for l in range(i-j):
            if V[-l-1]<0:
                m.append(V[-l-1])
            else:
                t+=V[-l-1]
        m.sort(reverse=True)
        if len(m)>k-i:
            t+=sum(m[:len(m)-(k-i)])
       
        
        ans=max(ans,t)
print(ans)

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

Solution (Python):

import bisect

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

def calc(k_l, k_r):
	v_l = v_list[0:k_l]
	if k_r == 0:
		v_r = []
	else:
		v_r = v_list[-k_r:]
	

	v_s = v_l + v_r
	v_s.sort()
	
	minus_count = bisect.bisect_left(v_s, 0)
	
	k_d = min(K - k_l - k_r, minus_count)

	v_s = v_s[k_d:]

	return sum(v_s)

max = calc(0, 0)
nk_min = min(N, K)
for k_l in range(0, K + 1):
	for k_r in range(0, nk_min - k_l + 1):

		score = calc(k_l, k_r)
		if score > max:
			max = score
print(max)

Solution (Python):
import bisect
N, K = map(int, input().split())

V = [int(x) for x in input().split()]

ans = 0
for a in range(K+1):
    for b in range(K+1):
        max_CD = min(a + b, min(2*N, K) - (a+b))
        if max_CD < 0 or a + b > N:
            break
        vs = V[:a] + V[N-b:]
        vs.sort()
        i = bisect.bisect_left(vs, 0)
        
        ans = max(ans, sum(vs[min(i, max_CD):]))
print(ans)

Solution (Python):

def main():
    n, k = map(int, raw_input().split())
    vv = map(int, raw_input().split())
    best = 0
    for pop in xrange(min(n, k) + 1):
        ret = k - pop
        for i in xrange(pop + 1):
            aa = vv[:pop - i] + vv[n - i:]
            s = 0
            r = ret
            for a in sorted(aa):
                if r > 0 > a:
                    r -= 1
                else:
                    s += a
            best = max(best, s)
    print best


if __name__ == '__main__':
    main()

Solution (Python):
n, k = map(int, raw_input().strip().split())
v = map(int, raw_input().strip().split())

ans = 0
for a in xrange(k + 1):
    for b in xrange(k - a + 1):
        z = a
        if z > n: z = n
        l = []
        val = 0
        for i in xrange(z):
            l.append(v[i])
            val += v[i]
        if z < n:
            for i in xrange(n - 1, z - 1, -1):
                if n - i > b: break
                l.append(v[i])
                val += v[i]
        l.sort(reverse = True)
        rem = 0
        op = k - a - b
        while rem < op:
            if len(l) > 0:
                if l[-1] < 0:
                    val -= l[-1]
                    l.pop()
                    rem += 1
                else:
                    break
            else:
                break
        ans = max(ans, val)

print ans