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: Time Limit Exceeded

Solution code:
n, k = map(int, input().split())
listV = list(map(int, input().split()))
haveL=[]
memo={}
def maxTaker(haveL, listV, k):
    strH = "".join(list(map(str, haveL)))
    strV = "".join(list(map(str, haveL)))
    key = strH+strV+str(k)
    if key in memo:
        return memo[key]
    else:
        if k == 1:
            if haveL != [] and listV != []:
                haveL.sort()
                minHave = haveL[0]
                memo[key] = max(0, -1*minHave, listV[0], listV[-1])
                return max(0, -1*minHave, listV[0], listV[-1])
            elif haveL == []:
                memo[key] = max(0, listV[0], listV[-1])
                return max(0, listV[0], listV[-1])
            else:
                haveL.sort()
                minHave = haveL[0]
                memo[key] = max(0, -1*minHave)
                return max(0, -1*minHave)

        else:
            if haveL!=[] and listV!=[]:
                haveL.sort()
                minHave = haveL[0]
                listV1 = []
                listV1.extend(listV)
                listV2 = [minHave]
                listV1.extend([minHave])
                listV2.extend(listV)
                haveL1 = [listV[0]]
                haveL2 = [listV[-1]]
                haveL1.extend(haveL)
                haveL2.extend(haveL)
                memo[key] = max(0, maxTaker(haveL[1:], listV1, k-1)-minHave, maxTaker(haveL[1:], listV2, k-1)-minHave,
                                maxTaker(haveL1, listV[1:], k-1)+listV[0], maxTaker(haveL2, listV[:len(listV)-1], k-1)+listV[-1])
                return max(0, maxTaker(haveL[1:], listV1, k-1)-minHave, maxTaker(haveL[1:], listV2, k-1)-minHave, maxTaker(haveL1, listV[1:], k-1)+listV[0], maxTaker(haveL2, listV[:len(listV)-1], k-1)+listV[-1])
            elif haveL == []:
                haveL1 = [listV[0]]
                haveL2 = [listV[-1]]
                haveL1.extend(haveL)
                haveL2.extend(haveL)
                memo[key] = max(0, maxTaker(haveL1, listV[1:], k-1)+listV[0],
                                maxTaker(haveL2, listV[:len(listV)-1], k-1)+listV[-1])
                return max(0,maxTaker(haveL1, listV[1:], k-1)+listV[0], maxTaker(haveL2, listV[:len(listV)-1], k-1)+listV[-1])
            else:
                haveL.sort()
                minHave = haveL[0]
                listV1 = []
                listV1.extend(listV)
                listV2 = [minHave]
                listV1.extend([minHave])
                listV2.extend(listV)
                memo[key] = max(0, maxTaker(haveL[1:], listV1, k-1) -
                                minHave, maxTaker(haveL[1:], listV2, k-1)-minHave)
                return max(0, maxTaker(haveL[1:], listV1, k-1)-minHave, maxTaker(haveL[1:], listV2, k-1)-minHave)


print(maxTaker(haveL, listV, k))

Submission status: Time Limit Exceeded

Solution code:

def do_action(q, temoto, value, k_remain):
    if k_remain == 0:
        return value
    a = b = c = d = e = -100000000
    # a
    if len(q) != 0:
        val = q[0]
        a = do_action(q[1:], temoto + [val], value + val, k_remain - 1)
    # b
    if len(q) != 0:
        val = q[-1]
        b = do_action(q[:-1], temoto + [val], value + val, k_remain - 1)
    # c
    if len(temoto) != 0:
        temoto.sort()
        val = temoto[0]
        c = do_action([val] + q , temoto[1:], value - val, k_remain - 1)
    # d
    if len(temoto) != 0:
        temoto.sort()
        val = temoto[0]
        d = do_action(q + [val], temoto[1:], value - val, k_remain - 1)
    # e
    e = do_action(q , temoto, value, k_remain - 1)

    return max(a,b,c,d,e)

n, k = map(int, input().split())
dat_v = map(int, input().split())
dat_v = list(dat_v)
val = do_action(dat_v, [], 0, k)
print(val)

Submission status: Time Limit Exceeded

Solution code:
import copy
from collections import deque

def dfs(i, k, v, x):
    if i >= k:
        return sum(x)
    x.sort()
    y = [0, 0, 0, 0]
    if len(v) > 0:
        p = v.popleft()
        xi = copy.copy(x)
        xi.append(p)
        y[0] = dfs(i + 1, k, v, xi)
        v.appendleft(p)
    if len(v) > 1:
        p = v.pop()
        xi = copy.copy(x)
        xi.append(p)
        y[1] = dfs(i + 1, k, v, xi)
        v.append(p)
    if len(x) > 0:
        p = x[0]
        xi = [x[i] for i in range(1, len(x))]
        v.appendleft(p)
        y[2] = dfs(i + 1, k, v, xi)
        _ = v.popleft()
        v.append(p)
        y[3] = dfs(i + 1, k, v, xi)
        _ = v.pop()
    return max(y)

n, k = map(int, input().split())
v = deque(list(map(int, input().split())))
x = []
ans = dfs(0, k, v, [])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from functools import lru_cache

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

@lru_cache()
def value(V,k,hands):
    hands=list(hands)
    V=list(V)
    if k==0:
        return sum(hands)
    else:
        retval=sum(hands)
        try:
            retval=max(value(tuple(V[1::]),k-1,tuple(sorted(hands+[V[0]]))),retval)
        except:
            pass
        try:
            p2=value(tuple(V[:-1:]),k-1,tuple(sorted(hands+[V[-1]])))
            retval=max(retval,p2)
        except:
            pass
        try:
            p3=value(tuple(V+[hands[0]]),k-1,tuple(hands[1::]))
            retval=max(p3,retval)
        except:
            pass
        try:
            p4=value(tuple([hands[0]]+V),k-1,tuple(hands[1::]))
            retval=max(p4,retval)
        except:
            pass
        return retval

print(value(tuple(V),K,tuple()))

Submission status: Time Limit Exceeded

Solution code:
from functools import lru_cache

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


def value(V,k,hands):
    if k==0:
        return sum(hands)
    else:
        retval=sum(hands)
        try:
            retval=max(value(V[1::],k-1,sorted(hands+[V[0]])),retval)
        except:
            pass
        try:
            p2=value(V[:-1:],k-1,sorted(hands+[V[-1]]))
            retval=max(retval,p2)
        except:
            pass
        try:
            p3=value(V+[hands[0]],k-1,hands[1::])
            retval=max(p3,retval)
        except:
            pass
        try:
            p4=value([hands[0]]+V,k-1,hands[1::])
            retval=max(p4,retval)
        except:
            pass
        return retval

print(value(V,K,[]))

Submission status: Accepted

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

R = min(N,K)
point = 0
max_point = 0
hand = []

for i in range(R+1):
    for a in range(i+1):
        if i==a:
            hand = V[:a]
        else:
            hand = V[:a]+V[-(i-a):]
        negahand = [k for k in hand if k < 0]
        negahand.sort()
        if K-i > len(negahand):
            trash = -sum(negahand)
        else:
            trash = -sum(negahand[:K-i])
        point = sum(hand) + trash
        max_point = max(max_point,point)

print(max_point)

Submission status: Accepted

Solution code:
[n,k],li = [list(map(int,i.split())) for i in open(0)] 
ans = 0
for i in range(1,min(n+1,k+1)):
    for j in range(i+1):
        l = li[:(i-j)] + li[n-j:]
        re_num = min(k-i,len(l))
        l.sort()
        f = 0
        for p in range(re_num):
            if l[p] > 0:
                break
            f += 1
        l = l[f:]
        ans = max(ans,sum(l))
print(ans)

Submission status: Accepted

Solution code:
# ABC128 D
from collections import deque

N,K=map(int,input().split())
V=list(map(int,input().split()))
V=V[:]+V[:]
def check(k):
    res=0
    # 連続する k(K,K-1,...)個の宝石をとる
    # K-k個まで捨ててよい
    for i in range(k+1):
        if k<N:
            v=V[N-k+i:N-k+i+k]
        else:
            v=V[:N]
        v.sort(reverse=True)
        for i in range(K-k):
            if not v:
                break
            if v[-1]<0:
                v.pop()
            else:
                break
        res=max(res,sum(v))
        if not k<N:
            break
    return res

res=0
for k in range(min(N,K)+1):
    res=max(res,check(k))
print(res)

Submission status: Accepted

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

r=min(n,k)
ans=0

for a in range(r+1):
    for b in range(r+1):
        jew=[]
        if a+b>r:
            break
        for i in range(a):
            jew.append(v[i])
        for i in range(n-1,n-b-1,-1):
            jew.append(v[i])
        
        if len(jew)==0:
            continue

        jew.sort(reverse=True)

        for i in range(k-(a+b)):
            if len(jew)>0:
                if jew[-1]<0:
                    jew.pop(-1)
                else:
                    break
        ans=max(ans,sum(jew))
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
#D - equeue
import sys 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N, K = map(int, readline().split())
V = list(map(int,readline().split()))

ans = 0
for l in range(min(K,N)+1):
    for r in range(min(K,N)-l+1):
        res = K - (l+r)
        minus = [] 
        total = sum(V[:l])+sum(V[N-r:])
        for i in range(l):
            if V[i] < 0:
                minus.append(V[i])        
        for i in range(r):
            if V[-i-1] < 0:
                minus.append(V[-i-1])
        minus.sort()
        S = len(minus)
        rep = sum(minus[:min(S+1,res)])
        total -= rep
        # print(l,r,total,rep)
        ans = max(total,ans)
print(ans)

Submission status: Accepted

Solution code:
#import math
#import itertools
#import numpy as np
from collections import deque


INT = lambda: int(input())
INTM = lambda: map(int,input().split())
STRM = lambda: map(str,input().split())
STR = lambda: str(input())
LIST = lambda: list(map(int,input().split()))
LISTS = lambda: list(map(str,input().split()))

def do():
    n,k=INTM()
    d=LIST()
    #q=deque(d)
    nkmin=min(n,k)
    stop=10**9
    ans=0
    for i1 in range(1,1+nkmin):
        for i2 in range(i1+1):
            temp=d[0:i2]+d[n-(i1-i2):]
            #print(temp,i1,i2)
            temp=sorted(temp)
            #print(temp,i1,i2)
            for i3 in range(i1):
                if temp[i3]>=0 or i3>=k-i1:
                    stop=i3
                    break
                stop=10**9
            if stop!=10**9:
                #print(temp[i3:],1)
                ans=max(sum(temp[i3:]),ans)
    
    print(ans)



if __name__=='__main__':
    do()

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
#from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

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

ans = 0
tmp_sum = 0

for i in range(1, min(K, N)+1):
	left = K-i
	for j in range(i+1):
		tmp = V[:j] + V[N-(i-j):]
		tmp.sort()
		idx = bisect_left(tmp, 0)
		ans = max(ans, sum(tmp) - sum(tmp[:min(idx, left)]))

print(ans)

Submission status: Accepted

Solution code:
def main():
    n, k = map(int, input().split())
    v = list(map(int, input().split()))
    reversed_v = [0] + v[::-1]
    v = [0] + v
    ans = -float("inf")
    for i in range(n + 1):
        for j in range(n + 1):
            if i + j > min(n, k):
                continue
            now_k = k - i - j
            if now_k < 0:
                continue
            q = []
            for l in range(1, i + 1):
                q.append(v[l])
            for l in range(1, j + 1):
                q.append(reversed_v[l])
            q.sort()
            for l in range(len(q)):
                if q[l] < 0 and now_k > 0:
                    q[l] = 0
                    now_k -= 1
            ans = max(ans, sum(q))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

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

w = deque(v)
ans = 0
for i in range(k+1):
    if i > n:
        break
    s = v[:i]
    for j in range(k+1-i):
        if j > n-i:
            break
        t = sorted(v[n-j:] + s, reverse=True)
        u = sum(t)
        for l in range(k+1-i-j):
            ans = max(ans, u)
            if not t:
                break
            u -= t.pop()
print(ans)

Submission status: Accepted

Solution code:
import sys

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

k=k0
if n<=k:
    v.sort()
    vsum=sum(v)
    kk=k-n
    vsum=0
    for i in range(n):
        if i>kk:
            vsum+=v[i]
        elif i<=kk and v[i]>0:
            vsum+=v[i]
    print(max(0,vsum))
    sys.exit()

vmax=-10**10

kk=k0
for k in range(kk):
    k2=kk-k-1
    
    vv=[[0]*(k+1) for i in range(k+1+1)]
    for i in range(k+1):
        vv[0][i]=v[n-k+i-1]
    vsum=sum(vv[0])
    vmax=max(vsum,vmax)
#    print("k:",k,"vsum:",vsum,"vmax:",vmax)
#    print(vv[0])
    vvv=vv[0].copy()
    vvv.sort()
    for i in range(min(k2,k+1)):
        if vvv[i]<0:
            vsum-=vvv[i]
    vmax=max(vsum,vmax)
#    print("k:",k,"vsum:",vsum,"vmax:",vmax)

    for i in range(k+1):
        vv[i+1]=vv[i].copy()
        vv[i+1].pop(0)
        vv[i+1].append(v[i])
        vsum=sum(vv[i+1])
        vmax=max(vsum,vmax)
#        print("k:",k,"vsum:",vsum,"vmax:",vmax)
#        print(vv[i+1])
        vvv=vv[i+1].copy()
        vvv.sort()
        for i in range(min(k2,k+1)):
            if vvv[i]<0:
                vsum-=vvv[i]
        vmax=max(vsum,vmax)
#        print("k:",k,"vsum:",vsum,"vmax:",vmax)
    
print(max(0,vmax))

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(min(n, k) - i + 1):
        lis = sorted(v[:i] + v[n - j:])
        for l in range(k - i - j + 1):
            ans = max(ans, sum(lis[l:]))
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 j in range(M-i+1):
    G = V[:i]+V[N-j:]
    G.sort()
    for j in range(K-i-j+1):
      ans = max(ans,sum(G[j:]))

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+1,k+1)):
    for j in range(min(n+1-i,k+1-i)):
        g = []
        x = 0
        while x < i:
            g.append(v[x])
            x += 1
        y = 0
        z = -1
        while y < j:
            g.append(v[z])
            y += 1
            z -= 1
        g.sort()
        x = k - i - j
        for z in range(min(len(g),x)):
            if g[z] < 0:
                g[z] = 0
            else:
                break
        ans = max(ans,sum(g))
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(1,min(N,K)+1):#i個とる
    for j in range(-i,1):
        lis = []
        for k in range(i):
            lis.append(V[j+k])
            #print(i,j,k,j+k)
        lis.sort(reverse=True)
        cnt = 0
        while (len(lis) != 0 and i+cnt < K and lis[-1] < 0):
            del lis[-1]
            cnt += 1
        ans = max(ans,sum(lis))
print(ans)

Submission status: Accepted

Solution code:
# equeue

from collections import deque
import heapq


def main():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    res = 0
    for pull in range(K+1):
        push = K - pull
        if push < 0 or push > N:
            continue
        for left_push in range(push+1):
            tmp_que = deque(V)
            tmp_heap = []
            heapq.heapify(tmp_heap)
            right_push = push - left_push
            for _ in range(left_push):
                heapq.heappush(tmp_heap, tmp_que.popleft())
            for _ in range(right_push):
                heapq.heappush(tmp_heap, tmp_que.pop())

            tmp_res = sum(tmp_que)
            for i in range(min(push, pull)):
                x = heapq.heappop(tmp_heap)
                if x >= 0:
                    heapq.heappush(tmp_heap,x)
                    break


            res = max(res, sum(tmp_heap))
    print(res)
    return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N,M=list(map(int,input().split()))
l=list(map(int,input().split()))
S=min(M,N)
ans=0
for i in range(S+1):
   for j in range(S-i+1):
      mem=l[0:i]+l[N-j:]
      for k in range(min((M-i-j),len(mem))):
         if min(mem)<0:
            mem.remove(min(mem))
      ans=max(ans,sum(mem))
print(ans)

Submission status: Accepted

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

ans = V[0]
for l in range(min(K, N)+1):
    for r in range(min(K, N)-l+1):
        v = V[:l] + V[N-r:]
        rest = K - (l + r)
        v.sort()
        tmp = 0
        for x in v:
            if rest and x < 0:
                rest -= 1
            else:
                tmp += x
        if ans < tmp:
            ans = tmp
print(ans)

Submission status: Accepted

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

y = min(n, k)

ans = 0

for i in range(y):
    cnt = 0
    heap = []
    for j in range(i+1):
        if v[j] < 0:
            heap.append(v[j])
            ans = max(ans, cnt)
        cnt += v[j]
        ans = max(ans, cnt)

    rest = k - i - 1
    right = n - i - 1
    for r in range(min(rest, right)+1):
        index = -1
        cnt2 = cnt
        heap2 = heap[:]
        for _ in range(r):
            cnt2 += v[index]
            if v[index] < 0:
                heap2.append(v[index])
            index -= 1

        ans = max(ans, cnt2)
        rest2 = rest - r
        heap2.sort()
        for o in range(rest2):
            if o >= len(heap2):
                break
            cnt2 -= heap2[o]
            ans = max(ans, cnt2)

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
result = 0
for a in range(N + 1):
    for b in range(N + 1):
        if a + b > K or a + b > N:
            break
        out = V[:a] + V[N-b:]
        out.sort()
        sum_val = sum(out)
        for i in range(min(a + b, K - a - b)):
            if out[i] >= 0:
                break
            sum_val -= out[i]
        result = max(result, sum_val);
print(result)

Submission status: Accepted

Solution code:
import heapq

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

ans = 0
for i in range(min(n, k)+1):  # a+b
    for a in range(i+1):  # 操作A
        b = i - a  # 操作B
        L = V[:a] + V[n-b:]
        heapq.heapify(L)
        total = sum(L)
        for j in range(k-i):
            if not L:
                break
            if L[0] >= 0:
                break
            total -= heapq.heappop(L)
        ans = max(ans, total)

print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
v = list(map(int, input().split()))
vv = [0] * (n + 1)
for i in range(n):
    vv[i + 1] = vv[i] + v[i]
sumv = vv[n]
ans = 0
for l in range(n):
    for r in range(l - 1, n):
        c = r - l + 1
        if n - c > k:
            continue
        x = []
        value = sumv - (vv[r + 1] - vv[l])
        for i in range(n):
            if not l <= i <= r:
                x.append(v[i])
        x.sort()
        for i in range(max(0, min(k - (n - c), len(x)))):
            if x[i] < 0:
                value -= x[i]
            else:
                break
        ans = max(value, ans)
print(ans)

Submission status: Accepted

Solution code:
import heapq, copy
n, k = map(int, input().split())
v = list(map(int, input().split()))
ans = -10 ** 10
for a in range(min(n, k) + 1):
    for b in range(min(n, k) - a + 1):
        have = []
        
        for i in range(a):
            have.append(v[i])
        for i in range(b):
            have.append(v[n-i-1])

        heapq.heapify(have)
        
        for c in range(k - a - b):
            if len(have) <= 0:
                break
            item = heapq.heappop(have)
            if item >= 0:
                have.append(item)
                break
        ans = max(ans, sum(have))

print(ans)

Submission status: Accepted

Solution code:
import heapq, copy
n, k = map(int, input().split())
v = list(map(int, input().split()))
ans = -10 ** 10
for a in range(min(n, k) + 1):
    have = []
    for i in range(a):
        have.append(v[i])

    o_have = copy.deepcopy(have)

    for b in range(min(n, k) - a + 1):
        for i in range(b):
            have.append(v[n-i-1])

        heapq.heapify(have)
        # print(1, have)
        for c in range(k - a - b):
            if len(have) <= 0:
                break
            item = heapq.heappop(have)
            # print(c, item, have)
            if item >= 0:
                have.append(item)
                break
        ans = max(ans, sum(have))
        # print(2, have, ans, a, b)
        have = copy.deepcopy(o_have)

print(ans)

Submission status: Accepted

Solution code:
import heapq, copy
n, k = map(int, input().split())
v = list(map(int, input().split()))
ans = -10 ** 10
for a in range(min(n, k) + 1):
    for b in range(min(n, k) - a + 1):
        have = []
        for i in range(a):
            have.append(v[i])
        for i in range(b):
            have.append(v[-i-1])

        tmp = sum(have)
        # heapq.heapify(have)
        have.sort()
        ans = max(ans, tmp)

        for c in range(k - a - b):
            if c >= len(have):
                break
            item = have[c]
            if item >= 0:
                break

            tmp -= item
            ans = max(ans, tmp)

print(ans)

Submission status: Accepted

Solution code:
import heapq, copy
n, k = map(int, input().split())
v = list(map(int, input().split()))
ans = -10 ** 10
for a in range(k + 1):
    for b in range(k - a + 1):
        if a + b > min(k, n):
            break
        # print(a, b)
        have = v[:a] + v[n-b:]
        # print(have)

        tmp = sum(have)
        ans = max(ans, tmp)

        have.sort()

        c = k - a - b

        for item in have:
            if c <= 0:
                break
            c -= 1
            if item >= 0:
                break

            tmp -= item
            ans = max(ans, tmp)

print(ans)

Submission status: Accepted

Solution code:
import heapq, copy
n, k = map(int, input().split())
v = list(map(int, input().split()))
ans = -10 ** 10
for a in range(k + 1):
    for b in range(k - a + 1):
        if a + b > min(k, n):
            break
        # print(a, b)
        have = v[:a] + v[n-b:]
        # print(have)

        tmp = sum(have)
        ans = max(ans, tmp)

        have.sort()

        c = k - a - b

        for item in have:
            if c <= 0:
                break
            c -= 1
            if item >= 0:
                break

            tmp -= item
        ans = max(ans, tmp)

print(ans)

Submission status: Accepted

Solution code:
import bisect

N, K = [int(x) for x in input().split()]
V = [int(x) for x in input().split()]
M = min(N, K)

ans = 0
juwel = []
for l in range(M + 1):
    for r in range(M - l + 1):
        juwel = sorted(V[:l] + V[N - r:])
        s = bisect.bisect_left(juwel, 0)
        s = min(s, K - l - r)
        juwel = juwel[s:]
        ans = max(ans, sum(juwel))

print(ans)

Submission status: Accepted

Solution code:
# 解説を参考に作成
# import sys
# sys.setrecursionlimit(10 ** 6)
# import bisect
from collections import deque
import heapq


# from decorator import stop_watch
#
#
# @stop_watch
def solve(N, K, Vi):
    ans = 0
    for ab in range(min(N, K) + 1):
        for a in range(ab + 1):
            b = ab - a
            have = Vi[:a] + Vi[N - b:]
            have.sort()
            s = sum(have)
            for i in range(K - ab):
                if len(have) <= i:
                    break
                elif have[i] < 0:
                    s += abs(have[i])
                else:
                    break
            ans = max(ans, s)
    print(ans)


if __name__ == '__main__':
    N, K = map(int, input().split())
    Vi = [int(i) for i in input().split()]
    solve(N, K, Vi)

    # # test
    # import random
    # from func import random_str
    # N, K = 100, 50
    # Vi = [random.randint(-(10 ** 7), 10 ** 7) for _ in range(N)]
    # solve(N, K, Vi)

Submission status: Accepted

Solution code:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

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 I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n,k=LI()
  v=LI()

  ans=0
  for i in range(k):
    if i+1<n:
      for l in range(i+1):
        r=i-l
  
        _ans=0
        _v=[]
        for x in range(l+1):
          _ans+=v[x]
          _v.append(v[x])
        for x in range(r):
          _ans+=v[n-x-1]
          _v.append(v[n-x-1])

        _v.sort()
        for j in range(min(len(_v),k-i-1)):
          if _v[j]<0:
            _ans-=_v[j]
          else:
            break
        # print(_v,l,r,_ans)
        ans=max(ans,_ans)
    else:
      _v=v.sort()
      _ans=sum(v)
      _k=n-k-1
      for j in range(_k):
        if _v[j]<0:
          _ans-=_v[j]
        else:
          break
      ans=max(ans,_ans)

  return ans

# main()
print(main())

Submission status: Accepted

Solution code:
'''
研究室PCでの解答
'''
import math
#import numpy as np
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7 #998244353
dir = [(-1,0),(1,0),(0,-1),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"

def main():
    n,k = map(int,ipt().split())
    v = [int(i) for i in ipt().split()]
    rv = v[::-1]
    ma = 0
    for ai in range(n+1):
        for bi in range(n-ai+1):
            d = k-ai-bi
            if d < 0:
                continue
            vs = v[:ai:]+rv[:bi:]
            vs.sort(reverse=True)
            for i in range(min(ai+bi,d)):
                if vs[-1] >= 0:
                    break
                else:
                    vs.pop()
            nm = sum(vs)
            if ma < nm:
                ma = nm

    print(ma)



    return None

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
Ans = -float('inf')
for a in range(K+1):
    for b in range(K+1):
        if a + b > min(K, N):
            break
        c = K - a - b
        A = V[:a] + V[N - b:]
        A.sort()
        ans = sum(A)
        for x in A:
            if c == 0:
                break
            if x >= 0:
                break
            if x < 0:
                c -= 1
                ans -= x
        Ans = max(ans, Ans)
print(Ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
ans=0
v=list(map(int,input().split()))
for i in range(min(n,k+1)):
    for j in range(min(n-i+1,k-i+1)):
        if j!=0:
            tmp=v[:i]+v[-j:]
        else:
            tmp=v[:i]
        tmp.sort()
        t=sum(tmp)
        for d in range(min(k-i-j,len(tmp))):
            if tmp[d]<0:
                t-=tmp[d]
        if t>ans:
            ans=t
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
n, k = map(int, input().split())
v = list(map(int, input().split()))
d = deque(v)

t = min(n, k)
score = 0
for a in range(t+1):
    for b in range(t-a+1):
        tmp_d = d.copy()
        jems = []
        for i in range(a):
            jems.append(tmp_d.pop())
        for i in range(b):
            jems.append(tmp_d.popleft())
        jems.sort()
        for i in range(min(len(jems), k-b-a)):
            if jems[i] < 0:
                jems[i] = 0
            else:
                break
        tmp_score = sum(jems)
        if tmp_score > score:
            score = tmp_score
print(score)