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



def main():
    
    def dbg(*something):
        if DEBUG:
            print(*something)


    #正の宝石を戻すことはない
    #負の宝石を戻すのは後半
    from sys import stdin
    from math import ceil,floor
    DEBUG = False
    N,K = list(map(int,stdin.readline().split()))
    V = list(map(int,stdin.readline().split()))
    
    max_value = 0
    dbg([i for i in range(3,-1,-1)])
    for getnum in range(1,min(N+1,K+1)):  #取る宝石の総数
        for a in range(getnum + 1):  #左から石を取る回数
            J = [0] * getnum #石
            b = getnum - a #右から石を取る回数
            for i in range(a):
                J[i] = V[i]
            for i in range(b):
                J[a+i] = V[-i-1]
            J.sort()
            #dbg(J,a,b)
            t = min(K-getnum,getnum) #捨てる石
           
            for i in range(t): 
                if J[i] >= 0:
                    t = i
                    break
            #dbg(J,i,t,a,b,J[t:])
            tmp_max = sum(J[t:])

            max_value = max(max_value,tmp_max)
    print(max_value)



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
	N, K = map(int, input().split())
	V = list(map(int, input().split()))
	pick_num = min(N, K)
	INF = 10**9+7
	dp = [-INF]*(N+K+1)
	dp[0] = 0
	dp[1] = max(V[0], V[-1])
	for i in range(2, pick_num+1):
		for j in range(i+1):
			l = V[:j]
			r = V[-i+j:] if i != j else []
			tmp = sum(l+r)
			dp[i] = max(dp[i], tmp)
			this_list = list(l+r)
			this_list.sort()
			for trash in range(K-i+1):
				dp[i+trash] = max(dp[i+trash], tmp-sum(this_list[:trash]))
	ans = dp[0]
	for i in range(1, K+1):
		ans = max(ans, dp[i])
	print(ans)


if __name__ == '__main__':
	main()

Submission status: Accepted

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

ans = 0
for a in range(R):
    for b in range(R):
        if a+b > R: break
        tmpV = sorted(V[:a]+rV[:b])
        if R == 1: tmpV = [max(V[0],rV[0])]
        t = sum(tmpV)
        for i in range(min(len(tmpV),K-(a+b))):
            if tmpV[i] >= 0: break
            else: t -= tmpV[i]
        if ans < t: ans = t
print(ans)

Submission status: Accepted

Solution code:
n,k=[int(i) for i in input().split()]
v=[int(i) for i in input().split()]
res=0
for right in range(k+1):
    for left in range(min(n,k)-right+1):
        ans=[]
        ans+=v[:right]
        ans+=v[n-left:]
        ans.sort()
        for i in range(min(k-right-left,len(ans))+1):
            res=max(res,sum(ans[i:]))
print(res)

Submission status: Accepted

Solution code:
import bisect
from collections import deque
N, K = map(int, input().split())
D = list(map(int, input().split()))

ans = 0
for pull_num in range(K+1):
    if pull_num > N:
        continue
    push_num = K - pull_num
    for left_num in range(pull_num+1):
        right_num = pull_num - left_num
        left_D = D[:left_num];  right_D = D[N-right_num:]
        temochi = left_D + right_D
        temochi.sort()
        index = bisect.bisect_left(temochi, 0)
        if push_num >= index:
            ans = max(ans, sum(temochi[index:]))
        else:
            ans = max(ans, sum(temochi[push_num:]))
print(ans)

Submission status: Accepted

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

ans=0
for nab in range(1,min(N+1,K+1)):
    nr=K-nab
    for na in range(nab+1):
        nb=nab-na
        vt=sorted(V[:na]+V[N-nb:])
        for ncd in range(min(nr+1,nab+1)):
            np=sum(vt[ncd:])
            ans=max(ans,np)

print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
ans=[]
for i in range(k+1):
  x=v[0:i]
  for j in range(k-i+1):
    if i<=n-j:
      y=v[n-j:n]
    else:
      y=v[i:n]
    L=x+y
    L.sort()
    ct=0
    ct2=0
    for m in range(len(L)):
      if L[m]>=0:
        ct+=L[m]
      else:
        if ct2<k-i-j:
          ct2+=1
        else:
          ct+=L[m]
    ans.append(ct)
print(max(ans))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
v=[int(i) for i in input().split()]
ans=0
chk=[0,0]
c=[]
for x in range(min(n,k)+1):
    if x>0:
        chk[0]+=v[x-1]
        if v[x-1]<0:
            c.append(v[x-1])
    ans=max(ans,chk[0])
    d=[]
    chk[1]=0
    for y in range(min(n,k)+1):
        if x+y>=k or x+y>=n:
            break
        if y>0:
            chk[1]+=v[-y]
            if v[-y]<0:
                d.append(v[-y])
        ans=max(ans,chk[0]+chk[1])
        e=c+d
        e.sort(reverse=True)
        t=0
        for z in range(k):
            if x+y+z>k or len(e)==0:
                break
            if z>0:
                t+=-(e[-1])
                e.pop()
                ans=max(ans,chk[0]+chk[1]+t)
print(ans)

Submission status: Accepted

Solution code:
INF = float("inf")
nl = lambda: list(map(int, input().split()))
sl = lambda: input().split()
n = lambda: int(input())
s = lambda: input()

N, K = nl()
Vs = nl()

import bisect

R = min(K, N)
res = -INF
for l in range(R+1):
    for r in range(R+1-l):
        v = sorted(Vs[:l] + Vs[N-r:])
        i = bisect.bisect_left(v, 0)
        value = sum(v[min(i, K-l-r):])
        if value > res:
            res = value
print(res)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
rev = v[::-1]
leftsum = [0]
rightsum = [0]
s = 0
for i in v:
    s = s+i
    leftsum.append(s)
s = 0
for i in v[::-1]:
    s = s+i
    rightsum.append(s)

m = 0
kn = min(k,n)
if kn==0:
    print(0)
    exit(0)

for x in range(1,k+1):
    for a in range(x+1):
        if a>n:
            break
        for b in range(x-a+1):
            if (b+a)>n:
                break
            minus= [i for i in v[:a] if i<0]
            minus.extend([i for i in rev[:b] if i<0])
            minus.sort()
            cd = x-a-b
            tmp = leftsum[a]+rightsum[b]-sum(minus[:cd])
            m = max(m,tmp)

print(m)

Submission status: Accepted

Solution code:
n, k = map(int, raw_input().split())
V = map(int, raw_input().split())
achievable = 0
for i in range(1, k+1):
    #print "i=" + str(i)
    for l in range(-1, i):
        if l > n :
            break
        #print "l=" + str(l)
        candid = 0
        fail = False
        kr = k - i
        subV = V[0:l+1]
        negatives = [x for x in subV if x < 0]
        #print "kr=" + str(kr)
        if l == -1:
            pass
        else:
            candid += sum(subV)
            #print subV
        for r in range(n-1, n-i+l, -1):
            if l >= r:
                fail = True
                break
            candid += V[r]
            #print V[r]
            if V[r] < 0:
                negatives.append(V[r])
        if fail:
            continue
        negatives.sort(reverse=True)
        while len(negatives) > 0 and kr > 0:
            candid -= negatives.pop()
            kr -= 1
        achievable = max(achievable, candid)
print achievable

Submission status: Accepted

Solution code:
def v_and_num(queue):
  output = [(0,0)]
  for i in range(len(queue)+1):
    hand = queue[:i]
    hand = sorted(hand)
    for j in range(len(hand)):
      output.append((i+j,sum(hand[j:])))
      if hand[j] > 0:
        break
  return output


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

"""
left = D[:n//2+1]
right = list(reversed(D[n//2+1:]))

l = v_and_num(left)
r = v_and_num(right)
M = 0
for k1, v1 in l:
  for k2, v2 in r:
    if k1+k2 > k:
      continue
    if v1+v2 > M:
      M = v1+v2
      """

r = min(k,n)
M = 0
for a in range(r+1):
  for b in range(r+1-a):
    hand = D[:a] + D[-b:] if b!=0 else D[:a]
    hand = list(sorted(hand))
    i = 0
    for i in range(min(k-a-b+1,a+b)):
      if hand[i] > 0:
        break
    buf = sum(hand[i:])
    if buf > M:
      M = buf
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
            del nv[0]
        ans = max(ans,sum(nv))
print(ans)

Submission status: Accepted

Solution code:
def solve(n, k, v):
    best = 0
    r = min(n, k)
    for a in range(r+1):
        for b in range(r+1-a):
            w = v[:a]
            if b > 0:
                w += v[-b:]
            w = sorted(w)
            m = min(k-a-b, len(w))
            for i in range(m):
                if w[i] < 0:
                    w[i] = 0
            best = max(best, sum(w))
    return best

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

Submission status: Accepted

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

if N < K:
    ans = sum(V)
    V = sorted(V)
    i = 0
    while len(V) > i:
        if V[i] >= 0:
            break
        ans += abs(V[i])
        i += 1
    print(ans)
    exit()


ans = 0
for a in range(K,-1,-1):
    for i in range(a+1):
        left = V[:a-i]
        if i != 0:
            right = V[-i:]
        else:
            right = []
        lr = sorted(left+right)
        tans = sum(lr)
        for j in range(min(len(lr),K-a)):
            if lr[j] < 0:
                tans += abs(lr[j])
        ans = max(ans , tans)
print(ans)

Submission status: Accepted

Solution code:
inf = input().split()
N = int(inf[0])
K = int(inf[1])
line = [int(v) for v in input().split()]

ans = 0
if K<N:
  for k in range(K+1):
    for i in range(k+1):
      item = line[:i]+line[N-k+i:]
      item.sort()
      count = 0
      while count<K-k and item:
        if item[0]>0:
          break
        item = item[1:]
        count += 1
      s = sum(item)
      if s>ans:
        ans = s
else:
  line = [i for i in line if i>0]
  ans = sum(line)

print(ans)

Submission status: Accepted

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

R = min(N, K)

MAX_VALUE = 0

for a in range(R + 1):
  for b in range(R - a + 1):
    tmp = V[0:a]
    if b > 0:
      tmp.extend(V[-b:])

    tmp.sort()
    start = 0
    for i in range(min(len(tmp), K - a - b)):
      if tmp[i] >= 0:
        break
      start = i + 1
    MAX_VALUE = max(MAX_VALUE, sum(tmp[start:]))

print(MAX_VALUE)

Submission status: Accepted

Solution code:
import heapq

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

    m = min(N, K)

    ans = 0
    # take i items
    for i in range(m+1):
        # take a items from left
        for a in range(i+1):
            items = D[:a] + D[N-(i-a):]
            ans = max(ans, sum(items))
            heapq.heapify(items)
            # push items
            for _ in range(min(i, K-i)):
                head = heapq.heappop(items)
                if head > 0:
                    break
                ans = max(ans, sum(items))
    print(ans)

main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
import bisect
from collections import defaultdict

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

    max_value = -10**7
    for num_get in range(K+1):
        if num_get > N:
            continue
        max_return = K - num_get
        for num_left in range(num_get+1):
            num_right = num_get - num_left
            V_obtained = list(V_list[:num_left])
            V_obtained += list(V_list[N-num_right:])
            V_obtained = sorted(V_obtained)
            for num_return in range(max_return+1):
                value = sum(V_obtained[num_return:])
                if max_value < value:
                    max_value = value

            if len(V_obtained) == 0:
                value = 0
                if max_value < value:
                    max_value = value

    print(max_value)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
V = list(map(int,input().split()))
ans = 0
T = []
for i in range(k+1):
    if i <= n:
        for a in range(i+1):
            L = V[0:a]+V[n-i+a:n]
            L.sort()
            cur = sum(L)
            for b in range(k-i):
                if b < len(L):
                    if L[b] < 0:
                        cur -= L[b]
            if cur > ans:
                ans = cur
    else:
        L = V
        L.sort()
        cur = sum(L)
        for b in range(k-i):
            if b < len(L):
                if L[b] < 0:
                    cur -= L[b]
        if cur > ans:
            ans = cur
print(ans)

Submission status: Accepted

Solution code:
inf = input().split()
N = int(inf[0])
K = int(inf[1])
line = [int(v) for v in input().split()]

ans = 0
if K<N:
  for k in range(K+1):
    for i in range(k+1):
      item = line[:i]+line[N-k+i:]
      item.sort()
      count = 0
      while count<K-k and item:
        if item[0]>0:
          break
        item = item[1:]
        count += 1
      s = sum(item)
      if s>ans:
        ans = s
else:
  line = [i for i in line if i>0]
  ans = sum(line)

print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
ansl = []
for i in range(min(k+1,n+1)):
    for j in range(i+1):
        v1 = v[0:j]
        v2 = v[n-(i-j):n]    
        v1.extend(v2)
        v1.sort()
        for x in range(k-i):
            if len(v1) != 0 and v1[0] < 0:
                del v1[0]
            else:
                break
        if len(v1) != 0:
            ansl.append(sum(v1))
        else:
            ansl.append(0)
ans = max(ansl)
print(ans)

Submission status: Accepted

Solution code:
import heapq

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

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

r = min(n,k)

s = []
for a in range(0,r+1):
    for b in range(0,r-a+1):
        if a > 0 and b > 0:
            vv = v[0:a] + v[n-b:n]
        elif a > 0:
            vv = v[0:a]
        elif b > 0:
            vv = v[0:b]
        else:
            vv = [0]
        #print(vv)
        heapq.heapify(vv)
        t = 1
        while vv != [] and vv[0] < 0 and t <= k-a-b:
            _ = heapq.heappop(vv)
            t += 1
        s.append(sum(vv))

print(max(s))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
 
n,max_k=list(map(int, input().split()))
d=list(map(int, input().split()))
answer=0
for k in range(1,max_k+1):
    for a in range(k+1):
        for b in range(k-a+1):
            if a+b<=k-a-b:
                continue
            if n<=a+b:
                in_hand=d
            else:
                in_hand=d[:a]
                in_hand+=d[n-b:]
            in_hand=sorted(in_hand)
            answer=max(answer,sum(in_hand[k-a-b:]))
print(answer)

Submission status: Accepted

Solution code:
#D問題
N, M=map(int, input().split())
V = input().split()
V_i = [int(i) for i in V]

ans = 0
for i in range(M+1):
    for j in range(M+1-i):
        if i+j >N:
            break;
        num = 0
        dump_num = []
        for k in range(i):
            num += V_i[k]
            dump_num.append(V_i[k])
        for k in range(N-1,N-j-1,-1):
            num+=V_i[k]
            dump_num.append(V_i[k])
        dump_num.sort()
        for k in range(M-i-j):
            if k >= len(dump_num):
                break;
            if dump_num[k] >= 0:
                break;
            num -= dump_num[k]
        
        if num >= ans:
            ans = num
print(ans)

Submission status: Accepted

Solution code:
import sys
import math 
ni = lambda: int(ns())
na = lambda: list(map(int, input().split()))
ns = lambda: input()

N,K = na()
que = na()
revque = que[::-1]

ans = 0
for a in range(min(N,K)+1):
    for b in range(min(K-a,N-a)+1):
        sum_q = que[:a] + revque[:b] if b>0 else que[:a]
        r = sum(sum_q)
        sum_q.sort()
        l = 0
        #print(sum_q)
        if sum_q:
            for i in range(min(K-(a+b),len(sum_q))):
                #print(i)
                if sum_q[i]>0:
                    l = i
                    break
                else:
                    r-=sum_q[i]
        if ans < r:
            ans = r
print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
def solve(string):
    n, k, *v = map(int, string.split())
    r = min(n, k)
    """
    for i in range(k + 1):
        for j in range(k - i + 1):
            base = sorted(v[:i] + v[max(n - k + i + j, i):])
            ans = max(ans, sum([b for l, b in enumerate(base) if b >= 0 or j <= l]))
    """

    def s(w):
        l = [0] * (k + 1)
        for i in range(1, k + 1):
            _w = sorted(w[:i], reverse=True)
            tmp = sum(_w)
            l[i] = max(l[i], tmp)
            j = 0
            while i + j < k and _w and _w[-1] < 0:
                j += 1
                tmp -= _w.pop()
                l[i + j] = max(l[i + j], tmp)
        return accumulate(l, func=max)

    *lefts, = s(v)
    *rights, = s(v[::-1])
    ans = max([lefts[i] + rights[k - i] for i in range(k + 1)])
    ans = min(ans, sum([_v for _v in v if _v > 0]))
    return str(ans)


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

Submission status: Accepted

Solution code:
def shift(l, n):
    return l[n:] + l[:n]

def main():
    n, k = map(int, input().split())
    v = list(map(int, input().split()))
    v_ = v[::-1]

    time = min(n, k)
    maxv = 0
    for a in range(time + 1):
        for b in range(time + 1 - a):
            sumlist = v[:a] + v_[:b]
            sumlist.sort()
            index = -1
            for i in range(min(len(sumlist), k - (a + b))):
                if sumlist[i] < 0:
                    index = i
            sumv = sum(sumlist[index+1:])
            if maxv < sumv:
                maxv = sumv
    print(maxv)

if __name__ == '__main__':
    main()

Submission status: Accepted

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


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

Submission status: Accepted

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

for a_i in range(min(k, len(v))+1):
    for b_i in range(min(k, len(v))-a_i+1):
        juwel = v[:a_i:] + v[len(v)-b_i::]
        juwel.sort()
        c = min(k - a_i - b_i, len(juwel))
        for i in range(c):
            if juwel[0] < 0:
                del juwel[0]
            else:
                break
        ans = max(ans, sum(juwel))
print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
ans=0
for x in range(1,1+min(N,K)):
    for y in range(1+min(x,K-x)):
        for z in range(1+x):
            pick=V[:z]
            if z-x<0:
                pick+=V[z-x:]
            pick.sort()
            now=sum(pick[y:])
            ans=max(now,ans)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

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

best = 0
for a in range(min([K, N]) + 1):
    for b in range(min([K, N]) - a + 1):
        L = V[:a] + V[N - b:]
        Lp = [i for i in L if i >= 0]
        Lm = [i for i in L if i < 0]
        Lm.sort()
        s = sum(Lp + Lm[min([len(Lm), K - a - b]):])
        best = max([best, s])

print(best)

Submission status: Accepted

Solution code:
###template###
import sys
def input(): return sys.stdin.readline().rstrip()
def mi(): return map(int, input().split())
###template###

N, K = mi()
Vs = list(mi())

#コードが簡単になるように、全ての宝石の合計価値をとっておく
valuesum = sum(Vs)

maxvalue = -(10**8)
#取らない場合（全てを「取らない」に入れる場合）はobtainedJewelsが空リストになって、sumも0になるだけなので問題ない。スライスに[:0]などと入れるのも、空リストになるだけなので問題なし
#全て取る場合：このループで考慮していないので、別でやる
for l in range(N): #範囲は0~N-1（全て取る場合もあるし、右端1個だけ取る場合もある)
  for r in range(N): #同様
     if l > r: continue #lとrが同値になってもいいが、lのが大きいのはNG
     remain = K-N+r-l+1 #残り手数
     if remain < 0: continue #残り手数マイナスは矛盾なので無視
     #取った宝石のリストを作って昇順に並べる
     obtainedJewels = sorted(Vs[:l] + Vs[r+1:])
     nowvalue = sum(obtainedJewels)
     #0～remain個の宝石を捨てた場合の価値をmaxvalueと比較していく
     for i in range(0, remain+1):
       maxvalue = max(maxvalue, nowvalue-sum(obtainedJewels[:i]))

#全て取る場合
if K>= N: #KがN以上ないと全て取ることは不可能
  remain = K-N
  obtainedJewels = sorted(Vs) #全て取る
   #0～remain個の宝石を捨てた場合の価値をmaxvalueと比較していく
  for i in range(0, remain+1):
   maxvalue = max(maxvalue, valuesum-sum(obtainedJewels[:i]))

#ここまでで、1個でもとると合計価値マイナスになるしかない場合（例えばN=K=1で宝石がマイナスとか）はマイナスになっている
print(max(0, maxvalue))

Submission status: Accepted

Solution code:
# まず、取れる分だけ取り出す
# 戻す（捨てる）操作は最後で良い。ソートして価値が低いものを捨てる
# 取り出す操作　＋　捨てる操作　＝ Kになる
N, K = map(int, input().split())
V = list(map(int, input().split()))

max_value = 0

for L in range(N+1):
  for R in range(N+1):
    if L+R > K:
      break
    if L+R > N:
      break
    get = V[:L]
    if R > 0:
      get += V[-R:]
    get.sort()
        
    rest = K - (L+R) # 残り操作回数
    # 価値が0以下を捨てる個数
    minus = sum((1 if x < 0 else 0 for x in get))
    if rest < minus:
      value = sum(get[rest:])
    else:
      value = sum((x for x in get if x > 0))
      
    if max_value < value:
      max_value = value
print(max_value)

Submission status: Accepted

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

ans = 0
for k in range(K+1):
    for a in range(min(k,n)+1):
        for b in range(min(k,n)-a+1):
            V = v[:a] + v[n-b:]
            V.sort()
            if k-a-b <= a+b:
                ans = max(ans,sum(V[k-a-b:]))
print(ans)

Submission status: Accepted

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

max_value = 0
for l in range(K + 1):
	for r in range(K + 1):
		if K < l + r or N < l + r:
			break
		hand = sorted(V[:l] + V[N - r:])
		for d in range(min(len(hand), K - l - r)):
			hand[d] = max(0, hand[d])
		max_value = max(max_value, sum(hand))
		#print(max_value, l, r, hand)
print(max_value)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
v = list(map(int, input().split()))
w = v[::-1]

res = 0
for l in range(N+1):
    for r in range(N+1):
        if l+r > N or l+r > K:
            break
        x = sorted(v[:l] + w[:r])
        for i in range(l+r):
            if x[i] > 0 or i == K-l-r:
                res = max(res, sum(x[i:]))
                break
print(res)

Submission status: Accepted

Solution code:
N,K=[int(i) for i in input().split()]
Vs=[int(i) for i in input().split()]
def maxchoice(N,K,Vs,acquire):
	maxval=0
	for ac in range(acquire+1):
		acVs=sorted(Vs[:ac]+Vs[-1:-(acquire-ac+1):-1],reverse=True)
		maxval=max(maxval,sum(acVs))
		for i in range(K-acquire):
			
			if acVs==[]:
				break
			if acVs[-1]<0:
				del acVs[-1]
				maxval=max(maxval,sum(acVs))
			else:
				maxval=max(maxval,sum(acVs))
				break
			
	return maxval

res=0
for acquire in range(1,min(N+1,K+1)):
	res=max(res,maxchoice(N,K,Vs,acquire))
print(res)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 12:47:17 2019

@author: YudNK
"""

N, K = map(int,input().split())
D = [int(i) for i in input().split()]
M = min(N, K)
max = 0
for a in range(M + 1):
    l = (M+1)//2 - a
    if l < 0:
        l = 0
    for b in range(l,M - a + 1):
        C = []
        t = K - (a + b)
        C.extend(D[:a])
        C.extend(D[N - b:])
        C2 = [i for i in C if i >= 0]
        if len(C) - len(C2) < t:
            C = C2
        else:
            C.sort()
            C = C[t:]
        if sum(C) > max:
            max = sum(C)
print(max)

Submission status: Accepted

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

ans = 0
for i in range(1, min(k + 1, len(d)+1)):
    s = 0
    for left in range(i+1):
        j = []
        if left > 0:
            j.extend(d[:left])
        if i-left > 0:
            j.extend(d[min(-(i - left), -1):])
        j = sorted(j)
        s = sum(j)
        for m in range(k - i):
            if len(j) <= m:
                break
            elif j[m] >= 0:
                break
            else:
                s -= j[m]
        ans = max(s, ans)
print(ans)

Submission status: Accepted

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

n_m=len([i for i in v if i<0])

if k>=n+n_m:
    ans=sum([i for i in v if i>=0])
else:
    a=[0]
    for l in range(1,k+1):
        for r in range(l+1):
            v_get=v[n-(l-r):]
            v_get+=v[:r]
            v_get.sort()
            z=k-l #残りの試行可能回数
            while v_get[0]<0 and z>0:
                v_get=v_get[1:]
                z+=-1
                if len(v_get)==0:
                    break
            a+=[sum(v_get)]
    ans=max(a)

print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np
sys.setrecursionlimit(1000000)
 
N,K = map(int,input().split())
VN =  [int(i) for i in input().split()]

ans = 0
temp = 0

for i in range(min(N,K)+1):
    for j in range(min(K-i,N-i)+1):
        now = 0
        if i + j > min(N,K):
            break
       
        tmp_list = []
        
        for l in range(i):
            now += VN[l]
            tmp_list.append(VN[l])
    
        for m in range(j):
            now += VN[N-1-m]
            tmp_list.append(VN[N-1-m])
        
        tmp_list.sort()
        
        for n in range(K-i-j):
            if n >= len(tmp_list):
                break
            if tmp_list[n] >= 0:
                break
            now -= tmp_list[n]
        ans = max(ans,now)

print(ans)

Submission status: Accepted

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

ans = 0
for i in range(k+1):
	for j in range(k-i+1):
		# print(i,j)
		a = v[:i]
		b = v[-j:]
		if len(b) == n:
			b = []
		ab = sorted(a+b+[0])
		idx = min(ab.index(0),idx_k-i-j)
		ans = max(ans,sum(ab[idx:]))
		# print(a,b,ab,idx,sum(ab[idx:]))
print(ans)

Submission status: Accepted

Solution code:
class MyClass():
    maxNumber = 0

    def roop(self, baseList, opeCount):
        listCount = len(baseList)
        roopMax = listCount if listCount < opeCount else opeCount
        for leftCount in range(0, roopMax):
            self.getMax(baseList[0: leftCount + 1], opeCount - leftCount - 1)

            for rightCount in range(1, roopMax - leftCount + 1):
                leftList = baseList[0: leftCount]
                rightList = baseList[listCount - rightCount : listCount]
                handList = leftList + rightList

                self.getMax(handList, opeCount - leftCount - rightCount)

                

    def getMax(self, handList, remainOpeCount):
        if len(handList) < 1:
            return

        maxVal = 0
        removeCount = 0

        if remainOpeCount > 0:
            handList.sort()
            for each in handList:
                if each < 0:
                    removeCount += 1
                    remainOpeCount -= 1
                    if remainOpeCount < 1:
                        break
        
        maxVal = sum(handList[removeCount:])
        self.maxNumber = max([maxVal, self.maxNumber])


count, opeCount = map(int, input().split())
baseList = list(map(int, input().split()))

my = MyClass()
my.roop(baseList, opeCount)
print(my.maxNumber)

Submission status: Accepted

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

ans = -10**9
R = min(N, K)
A = R
for a in range(0, A+1):
    B = R-a
    for b in range(0, B+1):
        if b>0:
            v = V[:a] + V[-b:]
        else:
            v = V[:a]
        
        v.sort()
        
        cnt = 0
        for vv in v:
            if vv<0:
                cnt += 1
            else:
                break
        ans = max(ans, sum(v[min(K-a-b, cnt):]))
        
print(ans)

Submission status: Accepted

Solution code:
import copy

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

max_value=0
for i in range(min(N,K)+1):
  for j in range(min(N,K)-i+1):
    tmp_get=[]
    tmp_get.extend(V[:i])
    if j!=0:
      tmp_get.extend(V[-j:])
    tmp_get.sort()

    for _ in range(K-(i+j)):
      if tmp_get!=[] and tmp_get[0]<0:
        tmp_get.pop(0)

    if sum(tmp_get)>max_value:
      max_value=sum(tmp_get)
          
print(max_value)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
able = min(N, K)
ans = 0
for a in range(able + 1):
	for b in range(able + 1 - a):
		if b == 0:
			have = V[:a]
		else:
			have = V[:a] + V[-b:]
		have.sort()
		for i in range(min(a + b, K - a - b) + 1):
			tmp = sum(have[i:])
			if ans < tmp:
				ans = tmp
print(ans)