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:
import numpy as np

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

mini = min(N, K)

ans = 0
for l in range(mini + 1):
    for r in range(mini + 1 - l):
        take = v[:l] + v[N - r:]
        ret = sorted(list(filter(lambda x: x < 0, take)))[:K-l-r]
        s = sum(take) - sum(ret)
        if s > ans:
            ans = s

print(ans)

Submission status: Accepted

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


def value(left, right):
    l_popped = v[:left]
    r_popped = v[-right:] if right > 0 else []
    popped = l_popped + r_popped

    negative = [x for x in popped if x < 0]
    negative.sort()
    
    rest = k - (left + right)
    pushed = negative[:rest]

    return sum(popped) - sum(pushed)


cap = min(n, k)
result = max(
    value(left, right)
    for left in range(k + 1)
    for right in range(cap - left + 1)
)

print(result)

Submission status: Accepted

Solution code:
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,n)-i+1):
  t=sorted(v[:i]+v[:~j:-1])
  while t and(k-i-j)*t[0]<0:t.pop(0);j+=1
  m=max(m,sum(t))
print(m)

Submission status: Accepted

Solution code:
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,n)-i+1):
  t=sorted(v[:i]+v[::-1][:j])
  while t and(k-i-j)*t[0]<0:t.pop(0);j+=1
  m=max(m,sum(t))
print(m)

Submission status: Accepted

Solution code:
from heapq import heappop, heappush, heapify

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

ans = 0
for i in range(min(n, k+1)):  #　右から
  for j in range(min(k-i+1, n-i+1)):  # 左から
    if i == 0:
      tmpl = vlist[:j]
    else:
      tmpl = vlist[:j] + vlist[-i:]
    heapify(tmpl)
    for _ in range(min(k - len(tmpl), len(tmpl))):
      _h = heappop(tmpl)
      if _h > 0:
        tmpl.append(_h)
        break
    tmpa = sum(tmpl)
    if tmpa > ans:
      ans = tmpa

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = [int(i) for i in input().split()]
V2 = V[::-1]
R = min(N, K)
ans = 0
for a in range(R+1):
    for b in range(R-a+1):
        c = K - (a + b)
        t = 0
        for v in sorted(V[:a]+V2[:b]):
            if v < 0 and c > 0:
                c -= 1
                continue
            t += v
        ans=max(t, ans)
print(ans)

Submission status: Accepted

Solution code:
n, k = [int(i) for i in input().split()]
V = [int(i) for i in input().split()]
plusList = [i >= 0 for i in V]
max_sum = 0

for ki in range(k+1):
    for mi in range(ki+1):
        for ii in range(ki-mi+1):
            if ki-mi-ii-1 >= n-ii:
                inHand = V
                ret_num = mi + ki-mi-ii-1 - (n-ii) + 1
            else:
                inHand = V[:ki-mi-ii]+V[n-ii:]
                ret_num = mi
            inHand.sort()    
            for jj in range(ret_num):
                if inHand != [] and inHand[0] < 0:
                    del inHand[0]
            if max_sum < sum(inHand):
                max_sum = sum(inHand)

print(max_sum)

Submission status: Accepted

Solution code:
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,n)-i+1):
  t=sorted(v[:i]+v[-j:]*(j>0))
  while t and(k-i-j)*t[0]<0:t.pop(0);j+=1
  m=max(m,sum(t))
print(m)

Submission status: Accepted

Solution code:
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,n)-i+1):
  t=sorted(v[:i]+v[-j:]*(j>0))[::-1]
  while t and(k-i-j)*t[-1]<0:t.pop();j+=1
  m=max(m,sum(t))
print(m)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
v_r = v[::-1]
ans = 0
for i in range(1,min(k+1,n+1)):
    for a in range(1,i+1):
        a_ = v[:a]
        b_ = v_r[:(i-a)]
        ab = a_+b_
        ab.sort()
        s = sum(ab)
        for j in range(k-i):
            if j<len(ab) and ab[j]<0:
                s -= ab[j]
            else:
                break
        ans = max(ans,s)
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(K+1):
    #print(i)
    for j in range(i+1):
        if N<=i:
            temp=sorted(V)
        elif j-i!=0:
            temp=sorted(V[:j]+V[j-i:])
        else:
            temp=sorted(V[:j])
        t=0
        for k in range(min(i,N)):
            if temp[k]>=0:
                t=k+1
                break
        #print(temp,t,j,j-i)
        #if t==0:
        #    print(":",0)
        if t>K-i:
            #print("1",temp[K-i:])
            #print("1",sum(temp[K-i:]))
            ans.append(sum(temp[K-i:]))
        elif (K-1-t)%2==1:
            if t>=2:
                #print("2",max(sum(temp[t-2:]),sum(temp[t:])))
                ans.append(max(sum(temp[t-2:]),sum(temp[t:])))
            else:
                #print("3",sum(temp[t:]))
                ans.append(sum(temp[t:]))
        else:
            #print("4",sum(temp[t-1:]))
            ans.append(sum(temp[t-1:]))
print(max(ans))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for i in range(1, min(N,K)+1):
    for j in range(i+1):
        W = sorted(V[:j]+V[N-i+j:])
        for k in range(min(i,K-i)+1):
            ans = max(ans, sum(W[k:]))
print(ans)

Submission status: Accepted

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

V_minus = len([v for v in V if v < 0])
K = min(K, N + V_minus)

vc_left = [0] * (K + 1)
minus_num = [0]
for i in range(N):
    if V[i] < 0:
        minus_num.append(-V[i])
        minus_num.sort(reverse=True)
    if i + 1 <= K:
        vc_left[i + 1] = max(vc_left[i + 1], sum(V[:i + 1]), vc_left[i])
    for j in range(1, len(minus_num)):
        if i+1+j <= K:
            vc_left[i+1+j] = max(vc_left[i + 1 + j], sum(V[:i + 1])+sum(minus_num[:j]), vc_left[i+j])

V.reverse()
vc_right = [0] * (K+1)
minus_num = [0]
for i in range(N):
    if V[i] < 0:
        minus_num.append(-V[i])
        minus_num.sort(reverse=True)
    if i + 1 <= K:
        vc_right[i + 1] = max(vc_right[i + 1], sum(V[:i + 1]), vc_right[i])
    for j in range(1, len(minus_num)):
        if i+1+j <= K:
            vc_right[i+1+j] = max(vc_right[i + 1 + j], sum(V[:i + 1])+sum(minus_num[:j]), vc_right[i+j])

ans_cand = [0] * (K+1)
for i in range(K+1):
    ans_cand[i] = vc_left[i] + vc_right[K-i]
ans_max = sum([v for v in V if v > 0])
print(min(max(ans_cand), ans_max))

Submission status: Accepted

Solution code:
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,n)-i+1):
  t=sorted(v[:i]+v[-j:]*(j>0))[::-1];c=k-i-j
  while t and c*t[-1]<0:t.pop();c-=1
  m=max(m,sum(t))
print(m)

Submission status: Accepted

Solution code:
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,n-i)+1):
  t=sorted(v[:i]+v[-j:]*(j>0))[::-1];c=k-i-j
  while t and c*t[-1]<0:t.pop();c-=1
  m=max(m,sum(t))
print(m)

Submission status: Accepted

Solution code:
N, K = [int(x) for x in input().split(" ")]
D = [int(x) for x in input().split(" ")]

combs = []
lim = min(N, K)
for a in range(0, lim + 1):
    for b in range(0, lim - a + 1):
          combs.append((a, b))

maxres = 0
for a,b in combs:
    elems = sorted(D[:a] + D[N-b:])
    negative = len([e for e in elems if e < 0])
    drop = min(negative, max(0, K - a - b))
    res = sum(elems[drop:])
    maxres = max(maxres, res)
print(maxres)

Submission status: Accepted

Solution code:
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*t[-1]<0:t.pop();c-=1
  m=max(m,sum(t))
print(m)

Submission status: Accepted

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

pick_max = min(N, K)
ans = 0
for left in range(pick_max + 1):
    for right in range(pick_max - left + 1):
        t = v[:left] + v[N - right:]
        m = sorted(filter(lambda x: x < 0, t))[:K - left - right]
        ans = max(ans, sum(t) - sum(m))
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter
from collections import deque
from functools import reduce
from pprint import pprint
# import statistics
import bisect
import copy
import fractions
import math
import random
import sys
import time
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def MI(): return map(int, sys.stdin.readline().split())
def II(): return int(sys.stdin.readline())
def IS(): return input()
def C(x): return Counter(x)
def GCD_LIST(numbers): return reduce(fractions.gcd, numbers)
def LCM_LIST(numbers): return reduce(LCM, numbers)
def LCM(m, n): return (m * n // fractions.gcd(m, n))
def unite(x, y):
    # それぞれのノードの根を求める
    x = root(x)
    y = root(y)
    if x == y:
        return
    # node[x]の根をyに変更する
    node[x] = y
def same(x,y): return bool(root(x) == root(y))
def root(x):
    if node[x] == x:  # xが根の場合
        return x
    else:
        node[x] = root(node[x])  # 経路圧縮
        return node[x]
def dfs(v):
    # ノードに訪れた
    visited[v] = True
    for v2 in range(n):
        if graph[v][v2] == False:  # そもそもvとv2が辺でつながっていない
            continue
        if visited[v2] == True:  # もう見た
            continue
        dfs(v2)


n, k = MI()
v = LI()
m = min(n, k)
ans = -INF
for a in range(m+1):
    for b in range(0, m+1-a):
        tmp_l = []
        for i in range(a):
            tmp_l.append(v[i])
        for j in range(b):
            tmp_l.append(v[-(j+1)])
        index = 0
        negative_sum = 0
        tmp_l.sort()
        while index < len(tmp_l) and index < k-(a+b):
            if tmp_l[index] < 0:
                negative_sum -= tmp_l[index]
            index += 1
        ans = max(ans, negative_sum + sum(tmp_l))
print(ans)

Submission status: Accepted

Solution code:
from heapq import heapify, heappop

N, K = map(int, input().split())
vl = list(map(int, input().split()))
vr = list(reversed(vl))
sum_L = [0]
for vv in vl:
    sum_L.append(sum_L[-1] + vv)

sum_R = [0]
for vv in vr:
    sum_R.append(sum_R[-1] + vv)

ans = 0
for pick in range(min(K, N) + 1):
    for to_remove in range(K + 1):
        if pick + to_remove > K: break
        for left in range(pick + 1):
            right = pick - left

            t = sum_L[left] + sum_R[right]

            q = vl[:left] + vr[:right]
            heapify(q)

            cnt = 0
            while cnt < to_remove and q:
                t -= heappop(q)
                cnt += 1
            ans = max(ans, t)
print(ans)

Submission status: Accepted

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

maxcost = min(N,K)
o = []

A = 0
while A <= maxcost:
    B = 0
    while A + B <= maxcost:
        a = V[:A]+V[N-B:]
        b = sorted(list(filter(lambda x:x<0,a)))[:K-A-B]
        #print(a,b)
        o.append(sum(a)-sum(b))
        B += 1
    A += 1

print(max(o))

Submission status: Accepted

Solution code:
import itertools as it
import collections as col
import heapq
import sys
sys.setrecursionlimit(10**9)
"""
N=int(input())
D=[]
for i in range(N):
  s,p=input().split()
  D.append((s, int(p), i+1))
D.sort(key=lambda d: (d[0], -d[1], d[2]))

for d in D:
  print(d[2])
"""
"""
N,M=map(int, input().split())
K=[]
S=[]
for i in range(M):
  k,*si=map(int, input().split())
  K.append(k)
  S.append(list(sorted(si)))
P=list(map(int, input().split()))

L=it.product([0,1], repeat=N)
cnt=0
#print(S)
for l in L:
  ok=True
  for i,si in enumerate(S):
    pi=P[i]
    sumS=len(list(filter(lambda it: l[it-1]==1, si)))
    #print(l, sumS)
    if sumS%2 != pi: ok=False
  if ok: cnt += 1
print(cnt)
"""
N,K=map(int,input().split())
V=list(map(int, input().split()))
M=max(N,K)

ans=0

#print(M)
for l in range(M+1):
  for r in range(M+1):
    if l+r<=min(N,K):
      H=[]
      U=list(V)
      H+=U[:l] + U[N-r:]
      H.sort(reverse=True)
      #print((l,r),U, H)
      for i in range(K-l-r):
        if H and H[-1] < 0: H.pop()
        else: break
      #print(sum(H), H)
      ans=max(ans, sum(H))
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

n,k = map(int,input().split())
v_in = list(map(int,input().split()))
v = deque(v_in)
m = -10000001
for i in range(k+1):
    for j in range(k-i+1):
        vv = deque(v_in)
        a = []
        for x in range(i):
            try:
                a.append(vv.popleft())
            except:
                break
        for y in range(j):
            try:
                a.append(vv.pop())
            except:
                break
        a.sort(reverse=True)
        for z in range(k-i-j):
            try:
                if a[-1] < 0:
                    a.pop()
                else:
                    break
            except:
                break
        tmp = sum(a)
        if tmp > m:
            m = tmp
print(m)

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(n-l+1):
        if l+r >k:
            break
        nv = v[:l] + v[n-r:]
        nv.sort()
        for i in range(k-l-r):
            if not nv or nv[0] >= 0:
                break
            nv.pop(0)
        ans = max(ans,sum(nv))
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-a, K-a)+1):
        c = K - a - b
        tmp = v_list[:a:] + v_list[N-b:]
        tmp.sort()
        trash = 0
        for i in range(min(c, len(tmp))):
            t = tmp[i]
            if t < 0:
                trash += t
            else:
                break
        ans = max(sum(tmp) - trash, ans)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()
from itertools import accumulate

def main():
    N, K = LI()
    V = LI()
    acc = [0] + list(accumulate(V))
    ans = 0
    for i in range(min(N, K) + 1):
        for p in range(i + 1):
            tmp = acc[p] + (acc[-1] - acc[-(i - p + 1)])
            sub = sorted(V[:p] + V[N - (i - p):])
            for s in sub[:K - i]:
                if s >= 0:
                    break
                tmp -= s
            ans = max(ans, tmp)
    return ans

print(main())

Submission status: Accepted

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

s = 0
for i in range(K + 1): # 左から取り出す回数
    for j in range(K + 1 - i): # 右から取り出す回数
        if i + j > N:
            continue
        
        a = V[:i] + V[N-j:]
        r = K - i - j # 戻すことのできる回数

        a.sort()
        for k in range(min(len(a)+1, r+1)):
            s = max(s, sum(a[k:]))

print(s)

Submission status: Accepted

Solution code:
import copy

n,m=map(int,input().split())
D=list(map(int,input().split(" ")))
answer=-99999999999
for i in range(m+1):
    take=i
    trash=m-i
    #print("take",take,"trash",trash)
    for j in range(take+1):
        if take>=n:
            #print("A")
            goukei=copy.copy(D)
        else:
            left=j
            right=j-take
            leftjewel=D[:left]
            rightjewel=D[right:]
            if right==0:
                rightjewel=[]
            
            #print("left",left,"right",right,"j",j,"take",take,"trash",trash)
            #print(leftjewel,rightjewel)
            goukei=leftjewel+rightjewel
        goukei.sort()
        for i in range(trash):
            if goukei!=[]:
                if goukei[0]<0:
                    del goukei[0]
        #print("最終",sum(goukei))
        if sum(goukei)>answer:
            #print("更新")
            answer=sum(goukei)
print(answer)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc128/tasks/abc128_d

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):
        # print(a)
        b = 0
        while b <= try_count - a:
            can_discard = K - a - b
            # print('{} {} {}'.format(a, b, can_discard))
            gets = D[:a] + D[N - b:]
            # print(gets)
            gets.sort()

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

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

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
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(i,li,ri,drop_num,ans,take_left,take_right,take,sum(take))
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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=[]
        #print("temoto_l",temoto)
        if nr>0:
            temoto.extend(V[(r+1):])            
        temoto=sorted(temoto)
        #tmp=v_total-gsum(l,r)
        tmp=sum(temoto)
        #print(temoto,tmp,v_total,gsum(l,r),r)
        for ss in range(K-len(temoto)):
            #print(ss)
            if ss>len(temoto)-1:
                break
            if temoto[ss]<0:
                tmp-=temoto[ss]
            else:
                break

        if tmp>res:
            res=tmp
            #print("koksin",res)
            #print(nl,nr)
            #print(l,r)
        

print(res)

Submission status: Accepted

Solution code:
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

    #print(toru)
    #print(sute)
    
    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)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heapify

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

# N jewels in dequeue D
# at most K operations
# 1 <= N <= 50
# 1 <= K <= 100
# -10000000 <= Vi <= 10000000

# Operation A, B: Remove left or right
# Operation C, D: Add to left or right

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)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
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:]
            # print("before:", jueries)
            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)
            # print("after:", jueries, s)
            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))  # type: int
    K = int(next(tokens))  # type: int
    V = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, K, V)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env 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)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/env pypy3

#import numpy as np
#import scipy, scipy.special

# Python 3 modules: https://docs.python.org/3/library/

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
# Use scipy for stats: https://docs.scipy.org/doc/scipy/reference/stats.html
# Before Python 3.5
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)

Submission status: Accepted

Solution code:
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[:]
        # print(v[:lhs],v[n-rhs:])
        for i in range(k+1-lhs-rhs):
            array.sort()
            ans.append(sum(array[i:]))
# print(ans)
print(max(ans))

Submission status: Accepted

Solution code:
#-*- coding:utf-8 -*-
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   # c回まで除去可能
        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)