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: Wrong Answer

Solution code:
from itertools import accumulate

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

dpl, dpr = [-10 ** 9] * (k + 1), [-10 ** 9] * (k + 1)
dpl[0] = dpr[0] = 0

for i in range(min(n, k)):
    i += 1
    vv = vvv[:i]
    vv.sort(reverse=True)
    sm = sum(vv)
    dpl[i] = max(dpl[i], sm)
    # print(i, vv, dpl)
    while i < k and vv and vv[-1] < 0:
        sm -= vv.pop()
        i += 1
        dpl[i] = max(dpl[i], sm)
    # print(i, vv, dpl)

vvv.reverse()

for i in range(min(n, k)):
    i += 1
    vv = vvv[:i]
    vv.sort(reverse=True)
    sm = sum(vv)
    dpr[i] = max(dpr[i], sm)
    # print(i, vv, dpr)
    while i < k and vv and vv[-1] < 0:
        sm -= vv.pop()
        i += 1
        dpr[i] = max(dpr[i], sm)
    # print(i, vv, dpr)

# print(dpl)
# print(dpr)
acl = list(accumulate(dpl, func=max))
acr = list(accumulate(dpr, func=max))
# print(acl)
# print(acr)
ans = 0
for i in range(k + 1):
    ans = max(ans, acl[i] + acr[k - i])
print(ans)

Submission status: Wrong Answer

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

ans=0
mai=len([t for t in v if t<0])           
v2=sorted(v)
if k>n:
    if k-n>=mai:
        ans=max(ans, sum(v2[mai:]))
    else:
        ans=max(ans, sum(v2[k-n:]))
    
for i in range(min(n+1,k+1)):
    for j in range(min(k-i+1,n-i)):
        if j==0:
            g=v[:i]
        else:
            g=v[:i]+v[-j:]
        g.sort()
        mai=len([t for t in g if t<0])
        if k-i-j>=mai:
            ans=max(ans, sum(g[mai:]))
            #print(g,sum(g[mai:]))
        else:
            ans=max(ans, sum(g[k-i-j:]))
            #print(g,sum(g[k-i-j:]))
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
Vi = [i+1 for i in range(len(V))]
V.extend(V)
Vi.extend(Vi)
ans = 0
for k in range(1, min(K, N)):
    # print(k)
    for s in range(len(V)):
        part_Vi = Vi[s:s+k]
        # print(len(part_Vi))
        if 1 not in part_Vi and N not in part_Vi:
            continue
        can_remove = K - k
        part_V = V[s:s+k]
        part_V = sorted(part_V)
        plus_i = 0
        for v in part_V:
            if v < 0:
                plus_i += 1
                can_remove -= 1
            else:
                break
            if can_remove <= 0:
                break
        # if sum(part_V[plus_i:]) == 50:
        #     print(part_V[plus_i:], k)
        ans = max(ans, sum(part_V[plus_i:]))
print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import*
from copy import*
n,k=map(int,input().split())
*v,=map(int,input().split())
v2=deepcopy(v)
motimono=[]
ans=[]
if k>=n:
    print(1)
else:
    v*=2
    for j in range(1,k+1):
        try:
            for i in range(n-j,n+1):
                motimono=v[i:i+j]
                ans.append(sum(motimono))
                heapify(motimono)
                for i in range(k-j):
                    if len(motimono)>0:
                        heappop(motimono)
                    ans.append(sum(motimono))
        except:
            continue
    print(max(ans))

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
v = list(map(int, input().split()))
cum = [0] * (n+1)

for i in range(n):
    cum[i+1] = cum[i] + v[i]

ans = cum[n]
cnt = 0
for i in range(n):
    for j in range(n):
        if i > j:
            continue
        l = (j - i + 1)
        if n - l > k:
            continue
        a = v[:i] + v[j+1:]
        a.sort()
        tmp1 = sum(a)
        # tmp = cum[n] - (cum[j+1] - cum[i])
        tmp = tmp1
        if tmp != tmp1:
            raise Exception()
        for x in range(k - (n-l)):
            if x >= len(a) or a[x] >= 0:
                break
            tmp -= a[x]
        ans = max([ans, tmp])
        cnt += 1

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2000000)
def do_action(q, temoto, value, k_remain):
    if k_remain == 0:
        return value
    a = b = c = d = e = -100000000

    # どっちを掘るか決める
    l_sum = r_sum = 0
    for i in range(min(k_remain, len(q))):
        if q[i] > 0:
            l_sum += q[i]
        if q[- (i + 1)] > 0:
            r_sum += q[- (i + 1)]

    # a
    if l_sum >= r_sum and l_sum > 0:
        if len(q) != 0:
            val = q[0]
            a = do_action(q[1:], temoto + [val], value + val, k_remain - 1)
    # b
    if r_sum <= l_sum and r_sum > 0:
        if len(q) != 0:
            val = q[-1]
            b = do_action(q[:-1], temoto + [val], value + val, k_remain - 1)

    temoto.sort()
    # 戻す可能性があるのは負のがあるときのみ
    if len(temoto) > 0 and temoto[0] < 0:
        if r_sum >= l_sum and r_sum > temoto[0]:
            # c
            if len(temoto) != 0:
                temoto.sort()
                val = temoto[0]
                c = do_action([val] + q , temoto[1:], value - val, k_remain - 1)
        if l_sum >= r_sum and l_sum > temoto[0]:
            # 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: Wrong Answer

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

def func(num, mode):
    ans = 0
    for i in range(1, num  +1):
        if mode == 0:
            tmp = vs[:i]
        else:
            tmp = vs[-i:]
        tmp.sort()
        # print(tmp, num, i, num - i)
        for j in range(num - i):
            if not tmp or tmp[0] >= 0:
                break
            tmp.pop(0)

        # print(tmp)
        ans = max(ans, sum(tmp))

    return ans



ans = 0
# print(min(k, n) + 1)
for i in range(min(k, n) + 1):
    tmp = func(i, 0) + func(min(k, n)- i, 1)
    ans = max(ans, tmp)
    # print(i, min(k, n)- i, func(i, 0), func(min(k, n)- i, 1))
print(ans)

Submission status: Wrong Answer

Solution code:
inf = - (10 ** 9)
n, k = map(int, input().split())
v = [int(i) for i in input().split()]
ans = inf
for left in range(k + 1):
    for right in range(k - left + 1):
        back = k - left - right
        if left + right <= n:
            vv = v[:left] + v[n - right:]
        else:
            vv = v
        vv.sort()
        back = k - min(left + right, len(vv))
        if (left == 0) & (right == 0):
            continue
        else:
            ans = max(sum(vv[back:]), ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def II(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
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 SI(): return input()
YN = lambda b: print('YES') if b else print('NO')
yn = lambda b: print('Yes') if b else print('No')

def main():
    N, K = LI()
    V_li = LI()

    maximum = 0
    for take_count in range(K+1):
        for take_left in range(take_count+1):
            took = V_li[:take_left] + ([] if take_count == take_left else V_li[-(take_count - take_left):])
            took = sorted(took)
            for trash_count in range(K - take_count):
                if took and took[0] < 0:
                    took.pop(0)
                else:
                    break
            if not took:  # empty
                 took = [0]
            maximum = max(maximum, sum(took))

    print(maximum)

main()

Submission status: Wrong Answer

Solution code:
N, K = list(map(int, input().split()))
Vs = list(map(int, input().split()))
Length = len(Vs)
maxv = 0
for i in range(K // 2):
    count = K - i
    for hoge in range(count):
        left = count
        right = 0
        for m in range(count + 1):
            if 0 <= left <= Length and 0 <= right <= Length:
                temp = sorted(Vs[:left] + Vs[Length - right:])
                for o in range(i):
                    if temp:
                        temp.pop(0)
                    else:
                        break
                sumv = sum(temp)
                left -= 1
                right += 1
                if sumv > maxv:
                    maxv = sumv

print(maxv)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
V = [int(i) for i in input().split()]
L = [0] * (N+1)
R = [0] * (N+1)
L_m = [[] for _ in range(N+1)]
R_m = [[] for _ in range(N+1)]

for i in range(1, N+1):
    L[i] = L[i-1] + V[i-1]
    R[i] = R[i-1] + V[-i]
    L_m[i] = L_m[i-1].copy()
    R_m[i] = R_m[i-1].copy()
    if V[i-1] < 0:
        L_m[i].append(V[i-1])
    if V[-i] < 0:
        R_m[i].append(V[-i])

ans = 0

for i in range(K+1):
    for l in range(K+1-i):
        r = K - i - l
        if l + r > N:
            ans = max(ans, R[-1] - sum(R_m[-1]))
            break
        if r < 0:
            break
        M = L_m[l] + R_m[r]
        M.sort()
        if len(M) >= i:
            m = sum(M[:i])
            a = L[l] + R[r] - m
            ans = max(ans, a)

print(ans)

Submission status: Wrong Answer

Solution code:
def sol(_inp=input):
    n,k=map(int,_inp().split())
    ds=list(map(int,_inp().split()))
    res=0
    for l in range(k+1):
        for r in range(k-l+1):
            cur=sum(ds[:l])+sum(ds[n-r:])
            negs=[i for i in ds[:l]+ds[n-r:] if i<0]
            rem=min(max(k-l-r,0),len(negs))
            cur-=sum(sorted(negs)[:rem])
            res=max(res,cur)
    return str(res)
print(sol())

Submission status: Wrong Answer

Solution code:
from copy import deepcopy

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

all_score = sum(V)
memo = {}

def dfs(queue, hand, depth):
    # print(queue, hand, depth)
    if depth == K:
        score = all_score - sum(queue)
        memo[queue] = score
        # print('return', queue, score)
        return score
    if queue in memo:
        # print('memo')
        return memo[queue]

    max_score = -1000000000
    if len(queue) > 0:
        # A
        A_queue = queue[1:]
        A_hand = deepcopy(hand)
        A_hand.append(queue[0])
        score = dfs(A_queue, A_hand, depth + 1)
        if score > max_score:
            max_score = score
        # B
        B_queue = queue[:-1]
        B_hand = deepcopy(hand)
        B_hand.append(queue[-1])
        score = dfs(B_queue, B_hand, depth + 1)
        if score > max_score:
            max_score = score


    for i in range(len(hand)):
        # C
        C_queue = (hand[i],) + queue
        C_hand = deepcopy(hand)
        C_hand = C_hand[:i] + C_hand[i+1:]
        score = dfs(C_queue, C_hand, depth + 1)
        if score > max_score:
            max_score = score

        # D
        D_queue = queue + (hand[i],)
        D_hand = deepcopy(hand)
        D_hand = D_hand[:i] + D_hand[i + 1:]
        score = dfs(D_queue, D_hand, depth + 1)
        if score > max_score:
            max_score = score

    memo[queue] = max_score
    # print(queue, max_score)
    return max_score

ans = dfs(V, [], 0)
print('0' if ans < 0 else ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

INF = 10000000 * 50 + 1

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

ans = -INF
for l in range(K + 1):
	for dr in range(K + 1 - l):
		r = N - dr
		if r <= l:
			break
		ms = np.sort(np.concatenate((V[:l], V[r:])))
		score = np.sum(ms)
		score -= np.sum(ms[ms < 0][:K-(l+dr)])
		ans = max(ans, score)

print(ans)

Submission status: Wrong Answer

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

rs = []
def check(k, v, current):
	global rs
	rs += [sum(current)]
	if 0 == k:
		return
	else:
		if current and (k < (K // 2 + 1)):
			mc = min(current)
			if mc < 0:
				i = current.index(mc)
				check(k - 1, v + [mc], current[:i] + current[i + 1:])
				check(k - 1, [mc] + v, current[:i] + current[i + 1:])
		if v:
			check(k - 1, v[1:], current + [v[0]])
			check(k - 1, v[:-1], current + [v[-1]])
		return

check(K, V, [])

print(max(rs))

Submission status: Wrong Answer

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

ans = 0
for a in range(K + 1):  # a回まで行う
    for i in range(a + 1):
        get = a - i
        rel = i
        if rel >= get:
            continue
        for j in range(get + 1):
            point = 0
            right = j
            left = get - right
            l = V[:left]
            r = V[N - right:]
            al = r + l
            # print(al, get)
            al.sort()
            point = sum(al[rel:])
            ans = max(ans, point)
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(x) for x in input().split(" ")]
D = [int(x) for x in input().split(" ")]
i = 0
j = len(D) - 1
memo = dict()

hands = set()

steps = 0

def maxSum(d, hands, k):
    if k == 0:
        return 0

    key = "{}::{}::{}".format(str(d), str(hands), k)
    if key in memo:
        return memo[key]
    
    patterns = [sum(hands)]

    if len(d) > 0:
        el = d[0]
        patterns.append(d[0] + maxSum(d[1:], hands.union(set([el])), k - 1))
        if len(d) > 1:
            el = d[-1]
            patterns.append(d[-1] + maxSum(d[:-1], hands.union(set([el])), k - 1))

    if hands:
        m = min(hands)
        newHand = hands.difference(set([m]))
        patterns.append(maxSum([m] + d, newHand, k - 1) - m)
        patterns.append(maxSum(d + [m], newHand, k - 1) - m)

    res = max(patterns)
    return res

print(maxSum(D, set(), K))

Submission status: Wrong Answer

Solution code:
from collections import deque

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

if K >= N:
    print(sum([v for v in dq if v >= 1]))
else:
    dq = deque(dq, maxlen=len(dq))
    print(100)

Submission status: Wrong Answer

Solution code:
from copy import deepcopy
N, K = map(int, input().split())
V = list(map(int, input().split()))
Lsum = [0]
Rsum = [0]
Lnegs = [[]]
Rnegs = [[]]
for i in range(N):
    Lsum.append(Lsum[i]+V[i])
    Rsum.append(Rsum[i]+V[N-i-1])
    Lnegs_cp = deepcopy(Lnegs[i])
    if V[i] < 0:
        Lnegs_cp.append(V[i])
        Lnegs_cp = sorted(Lnegs_cp)
    Lnegs.append(Lnegs_cp)
    Rnegs_cp = deepcopy(Rnegs[i])
    if V[N-i-1] < 0:
        Rnegs_cp.append(V[N-i-1])
        Rnegs_cp = sorted(Rnegs_cp)
    Rnegs.append(Rnegs_cp)

ans = -1001001001

for llim in range(N+1):
    rlim = N - llim
    lmax = -1001001001
    for k0 in range(min(K, llim)):
        kh = min(K, llim) - k0
        s0 = Lsum[k0]
        s1 = 0
        for l in range(min(len(Lnegs[k0]),kh)):
            s1 -= Lnegs[k0][l]
        lmax = max(lmax, s0+s1)
        rmax = -1001001001
        for k1 in range(min(K - k0, rlim)):
            kh = min(K - k0, rlim) - k1
            s0 = Rsum[k1]
            s1 = 0
            for l in range(min(len(Rnegs[k1]),kh)):
                s1 -= Rnegs[k1][l]
            rmax = max(rmax, s0+s1)
        ans = max(ans, lmax + rmax)

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for i in range(1,K+1):
    for j in range(i+1):
        rec = V[:i-j]+V[N-j:]
        rec.sort(reverse=True)
        away = max(min(i, K-i),0)
        for l in range(away+1):
            recsum = sum(rec[:i-l])
            if recsum > ans:
                ans=recsum
print(ans)

Submission status: Wrong Answer

Solution code:
import heapq


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

ans = 0
for kr in range(min(N, K)):
    for kl in range(min(N - kr, K - kr)):
        kp = K - kr - kl
        # print(kr, kl, kp)
        if kr != 0:
            vs = Vs[-kr:] + Vs[:kl]
        else:
            vs = Vs[:kl]
        
        length = len(vs)
        if length == 0:
            continue
        heapq.heapify(vs)
        # less than the number of outputs
        for i in range(min(kp, length, kr + kl)):
            if vs[0] < 0:
                heapq.heappop(vs)
            else:
                break
        value = sum(vs)
        ans = max(value, ans)

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for i in range(1,K+1):
    for j in range(i+1):
        rec = V[:i-j]+V[N-j:]
        rec.sort(reverse=True)
        away = max(min(0, i, K-i),0)
        for l in range(away+1):
            recsum = sum(rec[:i-l])
            if recsum > ans:
                ans=recsum
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

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

v = np.array(v)
cand = v[:k]

def calc(cand, res):
    res_ori = res
    #print("inp", cand, res)
#     if len(cand) <= 1:
#         return np.sum(cand)
    cand = list(cand)
    for i in range(len(cand)):
        if np.min(cand) >= 0:
            break
        if np.argmin(cand) != len(cand):
            if -np.min(cand)  > cand[-1]:
                if cand[-1] > 0 and res > 0:
                    res -= 1
                    cand.pop(np.argmin(cand))
                else:
                    cand.pop(np.argmin(cand))
                    cand = cand[:-1]
        if len(cand) == 0:
            break
    deletes = []
    if len(cand) > 0:
        while True:
            
            if cand[-1] < 0:
                deletes.append(cand[-1])
                cand = cand[:-1]
            else:
                break
            if len(cand) ==0:
                break
    if res > 0:
        s = np.sort(cand)
#         #print(s)
        anss = [-1000]
        for kk in range(0, res+1):
            tmp = max([max(anss), sum(s[kk:])])
            anss.append(tmp)
#         anss = [sum(s[kk:]) for kk in range(0,res + 1)]
        #print(len(anss), res_ori)
        while True:
            if len(anss) == res_ori + 2:
                break
            else:
                anss.append(anss[-1])
        anss = np.array(anss[1:])            
    else:
        anss = sum(cand)
        
    #print("out", anss)
    return anss

inds = np.arange(k + 1)
max_score = 0
for ind in inds:
    ind1 = np.arange(np.min([ind, n]))
    ind2 = np.arange(np.min([k, n]) - ind)
    a1 = v[ind1]
    a2 = v[::-1][ind2]
    res = 0
    if k > n:
        a2 = a2[:n - ind]
        res = k - n
    score1 = calc(a1, res)
    score2 = calc(a2, res)
    try:
        if len(score2) > 1:
            score2 = score2[::-1]
    except:
        pass
    score = score1 + score2
    score = np.max(score)
    #print("----", res)
    #print(score)
    if max_score < score:
        max_score = score
print(max_score)

Submission status: Wrong Answer

Solution code:

import sys
sys.setrecursionlimit(2000000)
def do_action(q, temoto, value, k_remain):
    if k_remain == 0:
        return value
    a = b = c = d = e = -100000000

    # どっちを掘るか決める
    l_sum = r_sum = 0

    for i in range(min(k_remain, len(q))):
        if q[i] > 0:
            l_sum += q[i]
        if q[- (i + 1)] > 0:
            r_sum += q[- (i + 1)]

    # a
    if l_sum >= r_sum and l_sum > 0:
        if len(q) != 0:
            val = q[0]
            a = do_action(q[1:], temoto + [val], value + val, k_remain - 1)
    # b
    if r_sum <= l_sum and r_sum > 0:
        if len(q) != 0:
            val = q[-1]
            b = do_action(q[:-1], temoto + [val], value + val, k_remain - 1)

    temoto.sort()
    # 戻す可能性があるのは負のがあるときのみ
    if len(temoto) > 0 and temoto[0] < 0:
        # 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: Wrong Answer

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

if k - k // 2 > n:
    for i in range(n):
        if v[i] >= 0:
            ans += v[i]
else:
    for i in range(k // 2 + 1):
        if k - i <= n:
            for j in range(k - i + 1):
                l = v[:k - i - j] + v[n - j:]
                l = sorted(l)[::-1]
                w = sum(l[:k - i - i])
                if ans < w:
                    ans = w
    

print(ans)

Submission status: Wrong Answer

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

left = np.cumsum([0] + v)
right = np.cumsum([0] + v[::-1])

results = []
for backn in range(min(50, k + 1)):
    t = min(n, k - backn)
    for shift in range(t + 1):
        p = v[:t - shift] + v[n - shift:]
        p.sort()
        value = sum(p[backn:])
        if (len(p) + backn) % 2 and len(p[backn:]) == 0:
            value = min(v[0], v[-1])
        results.append(value)
print(max(results))

Submission status: Wrong Answer

Solution code:
#coding:utf-8
N,K = map(int,input().split())
V = list(map(int,input().split()))
mx = 0
for k in range(1,K+1):
    for i in range(k+1):
        late = V[-(k-i):]
        if len(late)==N:
            late = []
        #print (k,V[:i],late)
        a = V[:i]+late
        a += [0]
        #print (a)
        a.sort()
        idx = min(a.index(0),K-k)
        sm = sum(a[idx:])
        #print (a,sm)
        mx = max(sm,mx)
        #print (mx)
print (mx)

Submission status: Wrong Answer

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, log2
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

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()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N, K = MAP()
V = LIST()
max_ = 0
for j in range(0, K+1, 2):
	# print("---j={}---".format(j))
	for i in range(j+1):  # jは残す数
		l = -i
		r = (j+K)//2 - i
		if l == 0 or r == -1:
			tmp_lis = V[l:r]
		else:
			tmp_lis = V[0:r] + V[l:]
		tmp_lis.sort(reverse=True)
		# print(tmp_lis)
		tmp = sum(tmp_lis[:j])
		max_ = max(max_, tmp)
print(max_)

Submission status: Wrong Answer

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

# 1手で左を取る
# 2手で左を捨てる

# 1手で右を取る
# 2手で右を捨てる

# +なら捨てる理由はない

def search(L, R, k):
    if L == R or k <= 0:
        return 0
    Q = [
        search(L + 1, R, k - 1) + V[L],
        search(L, R - 1, k - 1) + V[R]
    ]
    if V[L] < 0:
        Q.append(search(L + 1, R, k - 2))
    if V[R] < 0:
        Q.append(search(L, R - 1, k - 2))

    return max(Q)

print(search(0, N-1, K))

Submission status: Wrong Answer

Solution code:
if __name__ == '__main__':
    import sys
    input = sys.stdin.readline

    import copy


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

    vv = list(map(int, input().split()))
    ans = 0

    while k >= 1:
        for l in range((k+1)//2, k+1):
            for i in range(l+1):
                get_list = vv[:i]+ vv[n-(l-i):]
                get_list.sort(reverse=True)
                ans = max([ans, sum(get_list[:2*l-k])])
        k -= 1

    print(ans)

Submission status: Wrong Answer

Solution code:
N, K = list(map(int, input().split()))
Vs = list(map(int, input().split()))
Length = len(Vs)
maxv = 0
for i in range(K):
    if K // 2 >= i:
        count = K - i
        for hoge in range(count):
            left = count
            right = 0
            for m in range(count + 1):
                if left <= Length and right <= Length:
                    temp = sorted(Vs[:left] + Vs[Length - right:])
                    for o in range(i):
                        if temp:
                            temp.pop(0)
                        else:
                            break
                    sumv = sum(temp)
                    left -= 1
                    right += 1
                    if sumv > maxv:
                        maxv = sumv

print(maxv)

Submission status: Wrong Answer

Solution code:
import heapq


def main():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    if N <= K:
        V.sort()
        total = sum(V)
        ans = max(total, 0)
        for i in range(min(K-N, N)):
            total -= V[i]
            ans = max(ans, total)
        print(ans)
    else:
        left = [0] * (K+1)
        right = [0] * (K+1)
        for i in range(1, K+1):
            lv = V[:i]
            rv = V[-i:]
            lsum = sum(lv)
            rsum = sum(rv)
            left[i] = lsum
            right[i] = rsum
            lheap = list(lv[:-1])
            rheap = list(rv[1:])
            heapq.heapify(lheap)
            heapq.heapify(rheap)
            for j in range(1, i-1):
                lm = heapq.heappop(lheap)
                left[i] = max(left[i], lsum - sum(lv[-j:]) - lm)
                rm = heapq.heappop(rheap)
                right[i] = max(right[i], rsum - sum(rv[:j]) - rm)
        ans = 0
        for i in range(K+1):
            ans = max(max(left[i], 0) + max(right[K-i], 0), ans)
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
l = [0]
for i in range(1, K + 1): #左に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        #print("j=",j)
        a = []
        for m in range(min(i - j, N)):
            a.append(V[m])
        a.sort()
        s = 0
        for m in range(len(a)):
            if m >= j or a[m] >= 0:
                s += a[m]
        b = max(b, s)
    #print("b=",b)
    l.append(max(b, l[-1]))
#print(l)
r = [0]
for i in range(1, K + 1): #右に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        #print("j=",j)
        a = []
        for m in range(max(0, N - i + j), N):
            a.append(V[m])
        #print("s=",s)
        a.sort()
        s = 0
        for m in range(len(a)):
            if m >= j or a[m] >= 0:
                s += a[m]
        b = max(b, s)
    #print("b=",b)
    r.append(max(b, r[-1]))
#print(r)
ans = 0
for i in range(K + 1):
    ans = max(ans, l[i] + r[K - i])
print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import accumulate,chain,product
N,K = map(int,input().split())

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

av = tuple(chain((0,),accumulate(V)))


def left():
    yield (0,)
    for i in range(1,N+1):
        tmp = sorted(min(0, v) for v in V[:i])
        yield tuple(chain((0,), accumulate(tmp)))

left_cost = tuple(left())


def right():
    yield (0,)
    for i in reversed(range(N)):
        tmp = sorted(min(0, v) for v in V[i:])
        yield tuple(chain((0,), accumulate(tmp)))

right_cost = tuple(right())

def helper():
    for i in range(N+1):
        for j in range(N-i+1):
            d = K - i - j
            if d < 0:
                continue
            rev = av[i]+(av[N]-av[N-j])
            l,r = left_cost[i], right_cost[j]
            for k in range(d+1):
                yield rev - l[min(i,k)] - r[min(0,d-k)]
print(max(helper()))

Submission status: Wrong Answer

Solution code:
from collections import deque

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

    return n, k, vlist


def submit():
    n, k, vlist = read_input()

    maxvalue = 0
    for kk in range(1, k):
        # 左からi回宝石を取得する
        # 右からkk-i回宝石を取得する
        for i in range(kk + 1):
            getv = []
            minusv = []
            vq_temp = deque()

            for v in vlist:
                vq_temp.append(v)

            for j in range(i):
                if len(vq_temp) > 0:
                    vl = vq_temp.popleft()
                    if vl < 0:
                        minusv.append(vl)
                    else:
                        getv.append(vl)
                else:
                    break

            for j in range(kk - i):
                if len(vq_temp) > 0:
                    vr = vq_temp.pop()
                    if vr < 0:
                        minusv.append(vr)
                    else:
                        getv.append(vr)
                else:
                    break


            # k - kk回はminusを削除できる
            minusv.sort()
            for m in range(k - kk):
                if minusv:
                    minusv.remove(minusv[0])
                else:
                    break

            currvalue = sum(getv) + sum(minusv)

            if currvalue > maxvalue:
                maxvalue = currvalue

    print(maxvalue)

if __name__ == '__main__':
    submit()