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.



Sample input:
6 4
-10 8 2 1 2 6


Sample output:
14

Submission status: Accepted

Solution code:
# -*- coding:utf-8 -*-
import sys
import heapq


def solve():
    N, K = list(map(int, sys.stdin.readline().split()))
    Vs = list(map(int, sys.stdin.readline().split()))

    ans = 0
    for i in range(0, K+1):
        for j in range(0, K+1):
            if i+j > K: break
            if i+j > N: break
            #
            if i==0 and i==j:
                continue

            _Vs = Vs[::-1]
            have = Vs[0:i]+_Vs[0:j]
            have.sort(reverse=True)

            M = i+j
            while M < K:
                if len(have) == 0: break
                if have[-1] < 0:
                    have.remove(have[-1])
                    M += 1
                    continue
                break

            ans = max(ans, sum(have))

    print(ans)



if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

n,k = inpl()
v = inpl()
m = min(n,k)
ans = 0
for a in range(m+1):
    for b in range(m+1):
        if a+b > m:
            continue
        q = deque(v)
        tmp = []
        for i in range(a):
            tmp.append(q.popleft())
        for j in range(b):
            tmp.append(q.pop())
        if k - (a + b) > 0:
            tmp.sort()
            for i in range(k-(a+b)):
                if not tmp:
                    break
                if tmp[0] < 0:
                    tmp.pop(0)
                else:
                    break
        ans = max(ans, sum(tmp))
print(ans)

Submission status: Accepted

Solution code:
#D
from heapq import heappush,heappop
from collections import deque
import sys
n,k=map(int,input().split())
v=deque(list(map(int,input().split())))
w=[[] for i in range(n)]
answer=-100000000
for i in range(min(n+1,k+1)):
    for j in range(min(n-i+1,k-i+1)):
        h=[]
        
        for a in range(i):
            heappush(h,v[a])
        for a in range(j):
            heappush(h,v[n-1-a])
        for a in range(k-i-j):
            if h and h[0]<0:
                heappop(h)
            else:
                break
        answer=max(answer,sum(h))
print(answer)

Submission status: Accepted

Solution code:
import copy

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

# 左からのリスト
Vl=[0]
Dl=[[]]
for l in range(N):
    tmpV = sum(V[0:l+1])
    Vl.append(tmpV)
    tmpD =[]
    for i in range(l+1):
        if V[i] <= 0:
            tmpD.append(V[i])
    Dl.append(tmpD)

#print(Vl)
#print(Dl)

# 右からのリスト
Vr=[0]
Dr=[[]]
for r in range(N-1,-1,-1):
    tmpV = sum(V[r:])
    Vr.append(tmpV)
    tmpD =[]
    for i in range(N-1,r-1,-1):
        if V[i] <= 0:
            tmpD.append(V[i])
    Dr.append(tmpD)

#print(Vr)
#print(Dr)

max=0
# ここで比べる
for l in range(N+1):
    for r in range(N+1):
        if l+r > N:
            continue
        for d in range(len(Dl[l])+len(Dr[r])+1 ):
            #print(l,r,d)
            if l + r +d > K:
                continue
            else:
                tmpD=copy.copy(Dl[l])
                tmpD.extend(Dr[r])
                tmpD.sort()
                
                tmpDsum=-1*sum(tmpD[0:d])
                
                if Vl[l]+Vr[r]+tmpDsum > max:
                    max = Vl[l]+Vr[r]+tmpDsum
                #print(l,r,d,max)
print(max)

Submission status: Accepted

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

ans = 0
for i in range(1, K+1):
    if i > N:
        break
    for j in range(i+1):
        temp = V[:j] + V[N-(i-j):]
        temp = sorted(temp)
        for k in range(K-i):
            if k >= i:
                break
            if temp[k] < 0:
                temp[k] = 0
        ans = max(ans, sum(temp))
print(ans)

Submission status: Accepted

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

m = min(N,K)
ans = 0
for i in range(m+1):
    for a in range(i+1):
        b = i-a
        if b != 0:
            X = V[:a] + V[-b:]
        else:
            X = V[:a]
        X.sort()
        value = sum(X)
        for e in X[:min((K-i),a+b)]:
            if e < 0:
                value -= e
            else:
                break
        if value > ans:
            ans = value
print(ans)

Submission status: Accepted

Solution code:
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(i+1):
        Juel = V[:j] + V[N-i+j:]
        Juel.sort()
        sum_v = 0
        for k in range(min(K-i, i)):
            Juel[k] = max(Juel[k], 0)
        ans = max(ans, sum(Juel))
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
nk = min(n,k)

can = []
left = []

for i in range(nk+1):
  if i != 0:
    left.append(v[i-1])
  right = []
  for j in range(nk-i+1):
    if j != 0:
      right.append(v[-j])
    tmp = left + right
    tmp.sort()
    now = sum(tmp)
    rest = min(k-i-j,len(tmp))
    for h in range(rest):
      if tmp[h] < 0:
        now -= tmp[h]
    can.append(now)
print(max(can))

Submission status: Accepted

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

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

ans = 0
for l in range(min(N+1,K+1)):
    for r in range(min(N+1,K+1)-l):
        left = V[:min(l, N+1)] # 左からとったもの
        right = V[max(0, N-r):] # 右からとったもの

        if len(left) + len(right) > N: # 元の個数を超えているならそれはできないのでスキップ
            continue
        else:
            gem = left + right

        gem.sort()

        #捨てられる回数
        drop = min(K-l-r, len(gem))
        idx = 0
        total = sum(gem)
        while idx < drop:
            if gem[idx] < 0:
                total -= gem[idx]
                idx += 1
            else:
                break
        ans = max(ans, total)

print(ans)

Submission status: Accepted

Solution code:
n,k,*v=map(int,open(0).read().split());print(max(sum(sorted(v[:j]+v[n-i+j:])[min(sum(x<0for x in v[:j]+v[n-i+j:]),k-i):])for i in range(min(n,k)+1)for j in range(i+1)))

Submission status: Accepted

Solution code:
n,k,*v=map(int,open(0).read().split());a=0
for i in range(min(n,k)+1):
	for j in range(i+1):
		s=sorted(v[:j]+v[n-i+j:])
		a=max(a,sum(s[min(sum(x<0for x in s),k-i):]))
print(a)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
nk = min(n,k)
can = []
left = []
for i in range(nk+1):
  if i != 0:
    left.append(v[i-1])
  right = []
  for j in range(nk-i+1):
    if j != 0:
      right.append(v[-j])
    tmp = left + right
    tmp.sort()
    now = sum(tmp)
    rest = min(k-i-j,len(tmp))
    for h in range(rest):
      if tmp[h] < 0:
        now -= tmp[h]
    can.append(now)
    #print(i,j,now,tmp)
print(max(can))

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    a, p = LI()
    print((a*3+p)//2)
    return

#B
def B():
    n = II()
    sp = []
    for i in range(n):
        sp.append(input().split())
    another = [(s[0], -1 * int(s[1]),num) for num,s in enumerate(sp)]
    another.sort()
    for s,p,q in another:
        print(q+1)

    return

#C
def C():
    n, m = LI()
    ks = LIR_(m)
    p = LI()
    patern = itertools.product(range(2), repeat=n)
    ans = 0
    for on in patern:
        ki = [0 for i in range(m)]
        for num, oni in enumerate(on):
            if oni:
                for i,ksi in enumerate(ks):
                    ksi = ksi[1::]
                    if num in ksi:
                        ki[i] ^= 1
        for num, pi in enumerate(p):
            if pi != ki[num]:
                break
        else:
            ans += 1
    print(ans)

            
    return

#D
def D():
    N, K = LI()#random.randint(1,50),random.randint(1,100)
    v = LI()#[random.randint(-10 ** 2, 10 ** 2) for i in range(N)]
    ans = 0
    for a in range(min(N, K) + 1):
        for b in range(min(N, K) + 1):
            if a + b > min(K,N):
                break
            if a == b == 0:
                continue
            deletes = K - a - b
            left = v[:a]
            right = v[:-b-1:-1]
            x = left + right
            x.sort()
            tmp = sum(x)
            for delete in range(min(deletes, len(x))):
                if x[delete] >= 0:
                    break
                tmp -= x[delete]
            ans = max(ans,tmp)
    
    print(ans)
                

    return

#E
def E():
    return

#F
def F():
    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    a, p = LI()
    print((a*3+p)//2)
    return

#B
def B():
    n = II()
    sp = []
    for i in range(n):
        sp.append(input().split())
    another = [(s[0], -1 * int(s[1]),num) for num,s in enumerate(sp)]
    another.sort()
    for s,p,q in another:
        print(q+1)

    return

#C
def C():
    n, m = LI()
    ks = LIR_(m)
    p = LI()
    patern = itertools.product(range(2), repeat=n)
    ans = 0
    for on in patern:
        ki = [0 for i in range(m)]
        for num, oni in enumerate(on):
            if oni:
                for i,ksi in enumerate(ks):
                    ksi = ksi[1::]
                    if num in ksi:
                        ki[i] ^= 1
        for num, pi in enumerate(p):
            if pi != ki[num]:
                break
        else:
            ans += 1
    print(ans)

            
    return

#D
def D():
    N, K = LI()#random.randint(1,50),random.randint(1,100)
    v = LI()#[random.randint(-10 ** 2, 10 ** 2) for i in range(N)]
    ans = 0
    for a in range(min(N, K) + 1):
        for b in range(min(N, K) + 1):
            if a + b > min(K,N):
                break
            if a == b == 0:
                continue
            deletes = K - a - b
            left = v[:a]
            right = v[:-b-1:-1]
            x = left + right
            x.sort()
            tmp = sum(x)
            zero_index = bisect_left(x, 0)
            tmp -= sum(x[:min(zero_index,deletes)])
            ans = max(ans, tmp)
    
    print(ans)
                

    return

#E
def E():
    return

#F
def F():
    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

# 入力
n, k = li()
v = list(li())

# 個数m決め打ち
ans = 0
for m in range(n+1):
    rest = k
    rest -= m

    if rest < 0:
        continue

    # 左からi個、右からm-i個
    for i in range(m+1):
        a = v[:i] + v[n-m+i:]
        a.sort()
        suma = sum(a)

        # kを超えないようにマイナスを詰める
        for j in range(rest):
            if j >= len(a):
                break

            if a[j] < 0:
                suma += abs(a[j])
            else:
                break

        ans = max(ans, suma)

print(ans)

Submission status: Accepted

Solution code:
import sys
import bisect
input = sys.stdin.readline
N,K=map(int,input().split())
V=[int(x) for x in input().split()]
M=min(N,K)
ans=0
for a in range(M+1):
    for b in range(0,M+1-a):
        #print(a,b)
        if b != 0:
            #print(V[0:a],V[-b:])
            Get = V[0:a] + V[-b:]
            Get.sort()
            #print('bisect: %d' % bisect.bisect_left(Get,0))
            del Get[0:min(K-(a+b),bisect.bisect_left(Get,0))]
            ans=max(ans,sum(Get))
            #print(Get,sum(Get))
        else:
            Get = V[0:a]
            #print(V[0:a])
            Get.sort()
            del Get[0:min(K-(a+b),bisect.bisect_left(Get,0))]
            ans=max(ans,sum(Get))
            #print(Get,sum(Get))
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
Vs = list(map(int, input().split()))
rs = []
for i in range(0, min(N, K)+1):
  for j in range(0, min(N, K)-i+1):
    k = max(0, K-i-j)
    Vs2 = Vs[:i]+Vs[N-j:]
    VsN = [v for v in Vs2 if v < 0]
    if len(VsN) < k:
      r = sum(Vs2)-sum(VsN)
    else:
      r = sum(Vs2)-sum(sorted(VsN)[:k])
    rs.append(r)
r = max(rs)
print(r)

Submission status: Accepted

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

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

        lst = []
        if l > 0:
            lst += V[:l]
        if r > 0:
            lst += V[-r:]

        lst.sort()
        # print('lst', lst)
        max_drop = K - (l + r)
        for d in range(max_drop + 1):
            if d >= len(lst):
                break

            ans = max(sum(lst[d:]), ans)
print(ans)

Submission status: Accepted

Solution code:
import heapq as hq
n, k = map(int, input().split())
v = list(map(int, input().split()))*2
ans = -10**9
for i in range(1, n + 1):
    if i > k:
        continue
    tmp = -10**9
    for j in range(i + 1):
        value = 0
        stack = v[n+j-i:n+j].copy()
        hq.heapify(stack)
        value = sum(stack)
        for rep in range(k - i):
            if len(stack) == 0:
                break
            pick = hq.heappop(stack)
            if pick < 0:
                value -= pick
            else:
                break
        tmp = max(tmp, value)
    ans = max(ans, tmp)
print(ans)

Submission status: Accepted

Solution code:
#D問題
N,K = map(int,input().split())
V = list(map(int,input().split()))

R = min(N,K)


MAX = 0
for a in range(R+1):
    G = []
    for i in range(a):
        G.append(V[i])
    for b in range(R+1-a):
        H = G[:]
        for j in range(min(b,N-a)):
            H.append(V[N-j-1])
        H.sort()
        kari = sum(H)
        for k in range(K-(a+b)):
            if k >= a+b:
                break
            else:
                if H[k] >= 0:
                    break
                else:
                    kari+=(-H[k])
        MAX = max(MAX,kari)
        
print(MAX)

Submission status: Accepted

Solution code:
import bisect

n, k = map(int, input().split())
vs = list(map(int, input().split()))
res = 0
for i in range(k + 1):
    for j in range(k + 1):
        if i + j > min(k, n):
            continue
        ls = vs[:i]
        if j > 0:
            ls += vs[-j:]
        ls.sort()
        index = bisect.bisect(ls, 0)
        l = min(index, k - i - j)
        res = max(res, sum(ls[l:]))
print(res)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
n, k = map(int, input().split())
v = list(map(int, input().split()))
r = min(n, k)
ans = -float('inf')
for i in range(r+1):
    a = v[:i]
    for j in range(r+1-i):
        candi = a[:]
        if j != 0:
            candi += v[-j:]
        candi.sort()
        for t in range(k-i-j):
            if not 0 <= t < len(candi):
                break
            if candi[t] < 0:
                candi[t] = 0
            else:
                break
        candi = sum(candi)
        ans = max(candi, ans)
print(ans)

Submission status: Accepted

Solution code:
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 - l + 1):
		hand = []
		if l + r > n:
			break
        #handに左からl個
		hand = v[: l]
        #右からr個の要素を追加
		hand.extend(v[n - r:])
        #現時点でのhandの和をhand_sum
		hand_sum = sum(hand)  
		hand.sort()
        #hand_sum中の負の要素を詰めていく
		for i in range(min(k - l - r, l + r)):
			if hand[i] < 0:
			  hand_sum -= hand[i]
		ans = max(ans, hand_sum)

print(ans)

Submission status: Accepted

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

ANS=[]
c = 0
for i in range(min(n, k) + 1):
    for j in range(min(n, k) - i + 1):
        c += 1
        ans1 = V[:i]
        if j == 0:
            ans2 = []
        else:
            ans2 = V[-j:]
        A = ans1 + ans2
        A.sort()
        for l in range(k-(i+j)):
            if A != [] and A[0] < 0:
                A = A[1:]
        ANS.append(sum(A))

print(max(ANS))

Submission status: Accepted

Solution code:
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):
    bag = []
    bag += v[:a]
    bag += v[len(v)-b:]
    bag.sort()
    if len(bag) > 0:
      for c in range(k-a-b):
        if bag[0] < 0:
          bag.pop(0)
        if len(bag) == 0:
          break
    ans = max(ans, sum(bag))
      
print(ans)

Submission status: Accepted

Solution code:
import heapq

N,K = (int(i) for i in input().split())
V = list(map(int,input().split()))
minimum = min(N,K)

ans = 0
for i in range(minimum+1):
    for j in range(minimum-i+1):
        AB = []
        for k in range(i):
            heapq.heappush(AB,V[k])
        for k in range(j):
            heapq.heappush(AB,V[N-k-1])
        cnt = K - i - j
        if i == 0 and j == 0:
            continue
        while cnt > 0 and AB[0] < 0:
            heapq.heappop(AB)
            cnt -= 1
            if AB == []:
                break
        if sum(AB) > ans:
            ans = sum(AB)

print(ans)

Submission status: Accepted

Solution code:
#17:09
n,k = map(int,input().split())
v = list(map(int,input().split()))
'''
左からa個
右からb個
k-a-b個以内捨てて良し
'''
can = []
nk = min(n,k)
for a in range(nk+1):
  if a != 0:
    x.append(v[a-1])
  else:
    x = []
  for b in range(nk+1-a):
    if b != 0:
      y.append(v[-b])
    else:
      y = []
    z = x + y
    z.sort()
    r = k - a - b
    tmp = 0
    if r < a+b:
      if z[r] < 0:
        for i in range(r,a+b):
          tmp += z[i]
      else:
        for i in range(a+b):
          if z[i] >= 0:
            tmp += z[i]
    else:
      for i in range(a+b):
        if z[i] >= 0:
          tmp += z[i]
    can.append(tmp)
print(max(can))

Submission status: Accepted

Solution code:
#coding utf-8
N,K=map(int,input().split())
V =list(map(int,input().split())) 

dpl=[]
temp=[]
T =min(N,K)+1
ans=0
for i in range(T):
  for j in range(T-i):
    dpl.clear()
    if i>0:
      dpl.extend(V[0:i])
    if j>0:
      dpl.extend(V[N-j:N])
    dpl.sort()            
    for k in range(K-i-j+1):
      if dpl != [] and k>0:
        if dpl[0]<=0:
          del dpl[0]       
      if ans<sum(dpl):
        ans=sum(dpl)
      if dpl == [] or dpl[0]>0:
        break

print(ans)

Submission status: Accepted

Solution code:
import bisect


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

    best = 0
    for left in range(min(N, K) + 1):
        for right in range(min(N, K) + 1 - left):
            vs = sorted(V[:left] + V[len(V) - right:])
            first_pos = bisect.bisect_left(vs, 0)
            max_trash = K - left - right
            trash = min(first_pos, max_trash)
            value = sum(vs[trash:])
            if best < value:
                best = value
    print(best)


main()

Submission status: Accepted

Solution code:
# -*- coding:utf-8 -*-

def solve():
    N, K = list(map(int, input().split()))
    Vs = list(map(int, input().split()))

    """方針
    Dequeueから宝石をとる。最後に好きなだけ宝石を戻す。
    dp[i][j] := 左からi個、右からj個取ったときの最大値
    """
    dp = [[0 for _ in range(K+1)] for __ in range(K+1)]
    dp[0][0] = 0  # dpを使ってなくて草

    ans = -float("inf")
    for i in range(0, K+1):
        for j in range(0, K+1):
            if i+j > K: break
            if i+j > N: break
            if i==0 and j==0:
                ans = 0
                continue

            hasVs = Vs[0:i] + Vs[N-j:N]
            hasVs.sort(reverse=True)

            restK = K - (i+j)
            while restK > 0:
                restK -= 1
                if hasVs == []:
                    break
                if hasVs[-1] < 0:
                    hasVs.pop(-1)
                    continue
                break

            ans = max(ans, sum(hasVs))

    print(ans)



if __name__ == "__main__":
    solve()

Submission status: Accepted

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

maxi = 0
for i in range(min(N, K)):
    for o in range(i+2):
        hand = []
        for p in range(o):
            hand.append(V[p])
        for p in range(N-(i-o)-1, N):
            hand.append(V[p])
        hand.sort()
        for j in range(K-i-1):
            if len(hand) > 0:
                if hand[0] < 0:
                    del hand[0]
                else:
                    break
        ts = 0
        for k in hand:
            ts += k
        if ts > maxi:
            maxi = ts
print(maxi)

Submission status: Accepted

Solution code:
from heapq import heappop, heappush

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

        v = 0
        while cnt < K and len(heap) > 0:
            v = heappop(heap)

            if v >= 0:
                heappush(heap, v)
                break
            cnt += 1

        ans = max(ans, sum(heap))
print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
ans=0
for l in range(n):
	for r in range(l,n+1):
		toru = l+n-r
		if toru > k:
			continue
		li = v[:l]
		li.extend(v[r:])
		li.sort()
		s=sum(li)
		cnt=0
		while toru < k and len(li) > cnt:
			if li[cnt]>=0:
				break
			toru+=1
			s-=li[cnt]
			cnt+=1
		ans=max(ans,s)
		if s==19:
			print(l,r)
print(ans)

Submission status: Accepted

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

ab_max = min(n, k)
got_max = 0
for ab_i in range(ab_max+1):
    for a_i in range(ab_i+1):
        b_i = ab_i - a_i
        taken = v[:a_i] + v[-1:-(b_i+1):-1]
        taken.sort(reverse=True)
        cd_max = min(k-ab_i, ab_i)
        for cd_i in range(cd_max+1):
            if cd_i == 0:
                continue
            if taken[-1] >= 0:
                break
            else:
                taken.pop()
        got_sum = sum(taken)
        if got_sum > got_max:
            got_max = got_sum

print(got_max)

Submission status: Accepted

Solution code:
from collections import deque

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

V = deque(map(int,input().split(" ")))

def search(N,K,V,score):
    ans = 0
    for i in range(min(N,K)+1):
        for j in range(min(N,K)-i+1):
            score = []
            for a in range(i):#do operation A
                score.append(V[a])
            for b in range(j):#do operation B
                score.append(V[len(V)-b-1])
            score=sorted(score)
            counter = 0

            while(counter < K-i-j):#do operation C,D
                if len(score)== 0:
                    break;
                if score[0]<0:
                    score.pop(0)
                    counter +=1
                else:
                    break;   
            ans = max(ans,sum(score))

    return ans

score = []
ans = search(N,K,V,score)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
from copy import deepcopy
n, k = map(int, input().split())
v = deque(map(int, input().split()))
# 取り出せる最大回数
t = min(n, k)
ans = 0
# A,Bの操作の回数で全探索
for a in range(t + 1):
    for b in range(t + 1 - a):
        # 初期化
        vv = deepcopy(v)
        # 今持っている宝石たち
        belongings = []
        # 取り出していく
        for _ in range(a):
            if vv:
                jewelry = vv.popleft()
                belongings.append(jewelry)
        for _ in range(b):
            if vv:
                jewelry = vv.pop()
                belongings.append(jewelry)
        # ソートして、負の宝石は可能な限り筒に戻す
        belongings.sort()
        for i in range(a + b):
            if belongings[i] < 0 and i < (k - a - b):
                belongings[i] = 0
        ans = max(sum(belongings), ans)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
from copy import deepcopy
n, k = map(int, input().split())
v = deque(map(int, input().split()))
t = min(n, k)
ans = 0
for a in range(t + 1):
    for b in range(t + 1 - a):
        vv = deepcopy(v)
        belongings = []
        for _ in range(a):
            if vv:
                jewelry = vv.popleft()
                belongings.append(jewelry)
        for _ in range(b):
            if vv:
                jewelry = vv.pop()
                belongings.append(jewelry)
        belongings.sort()
        for i in range(a + b):
            if belongings[i] < 0 and i < (k - a - b):
                belongings[i] = 0
        ans = max(sum(belongings), ans)
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V_list = list(map(int, input().split()))

ans = 0
for A in range(min(N, K)+1):
    for B in range(min(N, K)-A+1):
        count = K - (A + B)
        v = []
        for i in range(A):
            v.append(V_list[i])
        for j in range(B):
            v.append(V_list[-(j+1)])
        v.sort()
        for k in range(min(count, len(v))):
            if v[k] < 0: 
                v[k] = 0
            else: 
                break
        if ans < sum(v):
            ans = sum(v)

print(ans)

Submission status: Accepted

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

loop=min([K+1,N+1])
lists=[]
for j in range(1,loop):
    for i in range(j+1):
        temp1 = V[:i]
        temp2 = V[N-(j-i):]
        temp =[]
        temp+=temp1
        temp+=temp2
        lists.append([temp,K-(i+((j-i)))])


max_value=0

for row in lists:
    ks = min([row[1],len(row[0])])
    sort_row = sorted(row[0])

    for k in range(ks+1):
        max_value=max([sum(sort_row[k:]), max_value])

print(max_value)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
v = list(map(int, input().split()))
m = min(n, k)
result = 0
for i in range(m + 1):
  for j in range(i + 1):
    t = v[:j]
    t.extend(v[n - (i - j):])
    t.sort(reverse = True)
    l = k - i
    while len(t) > 0 and l > 0 and t[-1] < 0:
      t.pop()
      l -= 1
    result = max(result, sum(t))
print(result)

Submission status: Accepted

Solution code:
def slove():
    import sys, heapq
    input = sys.stdin.readline
    n, k = list(map(int, input().rstrip('\n').split()))
    v = list(map(int, input().rstrip('\n').split()))
    ms = 0
    for i in range(1, min(k + 1, len(v) + 1)):
        for j in range(i + 1):
            t = []
            heapq.heapify(t)
            if j != 0:
                for w in v[:j]:
                    heapq.heappush(t, w)
            if -i+j != 0:
                for w in v[-i+j:]:
                    heapq.heappush(t, w)
            for _ in range(k-i):
                if len(t) != 0:
                    p = heapq.heappop(t)
                    if p >= 0:
                        heapq.heappush(t, p)
                        break
                else:
                    break
            ms = max(ms, sum(t))
    print(ms)


if __name__ == '__main__':
    slove()