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:
import numpy as np
from collections import defaultdict
from functools import reduce

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

class Interval():
    def __init__(self, li):
        self.li = li
        self.n = len(li)
        self.sum_li = [li[0]]
        for i in range(1, self.n):
            self.sum_li.append(self.sum_li[i-1] + li[i])

    def sum(self, a, b=None):
        if b is None:
            return self.sum(0, a)

        res = self.sum_li[min(self.n-1, b-1)]
        if a > 0:
            res -= self.sum_li[a-1]
        return res


res = 0
for k in range(K+1):
    for l in range(k+1):
        pos = 0
        neg = []
        for i in range(min(l, N)):
            if i >= N:
                break
            if V[i] >= 0:
                pos += V[i]
            else:
                neg.append(V[i])

        for i in range(min(k-l, N)):
            if i >= N:
                break
            v = V[N-i-1]
            if v >= 0:
                pos += v
            else:
                neg.append(v)

        # print(pos)

        for i, v in enumerate(sorted(neg)):
            if i < K-k:
                continue
            pos += v
        res = max(res, pos)

print(res)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, K, V):
    ans = 0
    for i in range(0, K//2):
        for j in range(i, K+1):
            l = V[:j-i]
            r = V[N-(K-j):]
            # print(j, K-j, l, r, K-i)
            ans = max(ans, sum(sorted(l+r,  reverse=True)[:K-2*i]))

        # print(i)
    return ans


def main():
    N, K = read_int_n()
    V = read_int_n()
    print(slv(N, K, V))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
a = 0 #左からaことる
b = 0 #右からbことる

ans = -10**10
while a <= min(k,n):
    while b <= min(k-a,n-a):
        plus = []
        minus = []
        for i in range(a):
            if v[i] >= 0:
                plus.append(v[i])
            else:
                minus.append(v[i])
        for i in range(b):
            if v[i] >= 0:
                plus.append(v[-1-i])
            else:
                minus.append(v[-1-i])
        plus.sort()
        minus.sort()
        temp = sum(plus) + sum(minus)
        m = k-a-b #取り出した後に残った操作回数
        for i in range(min(m,len(minus))):
            temp += -minus[i]
        m = m - min(m,len(minus)) #負の数を戻した後に残った操作回数
        if m != 0:
            if m%2 != 0:
                if len(minus) == 0 and len(plus) == 0:
                    temp = 0
                elif len(minus) == 0:
                    temp -= plus[0]
                elif len(plus) == 0:
                    temp += minus[-1]
                else:
                    if abs(minus[-1]) <= plus[0]:
                        temp += minus[-1]
                    else:
                        temp -= plus[0]
        if temp > ans:
            ans = temp
        b += 1
    a += 1
    b = 0
print(ans)

Submission status: Wrong Answer

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

ans = 0

for a in range(1,K+1) :
    for i in range(a+1) :
        G = []
        G.extend(V[:i])
        G.extend(V[len(V)-(a-i):])
        G = sorted(G)
        #print(G)
        G = G[(K-a):]
        ans = max(ans,sum(G))
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
# gcd
from fractions import gcd
# 切り上げ，切り捨て
# from math import ceil, floor
# リストの真のコピー（変更が伝播しない）
# from copy import deepcopy
# 累積和。list(accumulate(A))としてAの累積和
from itertools import accumulate
# l = ['a', 'b', 'b', 'c', 'b', 'a', 'c', 'c', 'b', 'c', 'b', 'a']
# S = Counter(l)  # カウンタークラスが作られる。S=Counter({'b': 5, 'c': 4, 'a': 3})
# print(S.most_common(2))  # [('b', 5), ('c', 4)]
# print(S.keys())  # dict_keys(['a', 'b', 'c'])
# print(S.values())  # dict_values([3, 5, 4])
# print(S.items())  # dict_items([('a', 3), ('b', 5), ('c', 4)])
from collections import deque
# import math
# from functools import reduce
#
# input関係の定義
# fin = open('in_1.txt', 'r')
# sys.stdin = fin
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().rstrip().split())
def lmi(): return list(map(int, input().rstrip().split()))
def li(): return list(input().rstrip())
# template


def iterate_tokens():
    for line in sys.stdin:
        for word in line.split():
            yield word


if __name__ == '__main__':

    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    V = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"

    # write code
    left = [-10 ** 9] * (K+10)
    right = [-10 ** 9] * (K + 10)
    left[0] = 0
    right[0] = 0
    left[1] = V[0]
    right[1] = V[-1]
    for i in range(2, K+1):
        tmp_max = 0
        for j in range(i // 2, i):
            tmp_V = V[:j]
            tmp_V.sort()
            if tmp_max < sum(tmp_V[i - 2 * j:]):
                tmp_max = sum(tmp_V[i - 2 * j:])
        # print(tmp_max)
        left[i] = tmp_max

    for i in range(2, K+1):
        tmp_max = 0
        for j in range(i // 2, i):
            tmp_V = V[-j:]
            tmp_V.sort()
            if tmp_max < sum(tmp_V[i - 2 * j:]):
                tmp_max = sum(tmp_V[i - 2 * j:])
        # print(tmp_max)
        right[i] = tmp_max
    tmp_ans = -10 ** 9
    ans = []
    # print(left)
    # print(right)
    for j in range(K+1):
        for i in range(j+1):
            if tmp_ans < left[i] + right[j - i]:
                tmp_ans = left[i] + right[j - i]
        ans.append(tmp_ans)
    print(max(ans))

Submission status: Wrong Answer

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

V_arr = [int(x) for x in input().split()]

ans = 0
for l in range(K+1):
    if l > N:
        continue
    l_arr = V_arr[:l]
    for r in range(K+1-l):
        if l == 0 and r == 0:
            continue
        if l+r >= N:
            continue
        r_arr = V_arr[N-r:]
        have_arr = sorted(l_arr+r_arr)
        delete_top = 0
        for d in range(K-l-r):
            if d >= l+r:
                break
            if have_arr[d] > 0:
                break
            delete_top = d+1
        ans = max(ans, sum(have_arr[delete_top:]))

print(ans)

Submission status: Wrong Answer

Solution code:
import heapq

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

max_v = -float('inf')
for a in range(min(k, n)):
    total = 0
    minus = []
    for i in range(a):
        total += vs[i]
        if vs[i] < 0:
            heapq.heappush(minus, vs[i])
    max_v = max(max_v, total)
    for b in range(min(k-a, n-a)+1):
        c = k - a - b
        if c < 0:
            break
        h = minus[:]
        t = total
        for i in range(b):
            t += vs[n-1-i]
            if vs[n-1-i] < 0:
                heapq.heappush(h, vs[n-1-i])
        for i in range(c):
            if h:
                v = heapq.heappop(h)
                t -= v
            else:
                break
        max_v = max(max_v, t)

print(max_v)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,datetime
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())

N,K = inpl()
vv = inpl()

ans = 0
for lnum in range(K+1):
    for rnum  in range(K-lnum+1):
        torukazu = vv[:lnum] + vv[N-rnum:]
        torukazu.sort()
        #print(torukazu)
        for sute in range(K-lnum-rnum+1):
            #print(sute,torukazu[sute:])
            tmp = sum(torukazu[sute:])
        ans = max(tmp,ans)

print(ans)

Submission status: Wrong Answer

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

p = min(n, k)

res = 0

for i in range(p, -1, -1):
        # kことる
        for l in range(i + 1):
                r = i - l
                # 左からl, 右からrとる
                q = []
                for w in range(l):
                        q.append(v[w])
                for w in range(n - r, n):
                        q.append(v[w])
                q = sorted(q)
                ans = sum(q)
                tmp = ans
                for w in range(min(p - i, len(q))):
                        tmp -= q[w]
                        ans = max(ans, tmp)
                res = max(res, ans)

print(res)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import math
import collections

N, K = map(int, sys.stdin.readline().rstrip().split(" "))
Vs = list(map(int, sys.stdin.readline().rstrip().split(" ")))
result = 0
for L in range(min(N, K)):
    for R in range(min(N - L, K - L)):
        gems = Vs[:L]
        if R > 0:
            gems += Vs[-R:]

        gems.sort()
        rest = K - L - R
        # print(L, R, gems)
        for _ in range(rest):
            if len(gems) >0 and gems[0] < 0:
                gems.pop(0)
            else:
                break
        # print(gems, sum(gems))
        result = max(result, sum(gems))
print(result)
exit(0)

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 = V[0:i - j]
        s = sum(a)
        #print("s=",s)
        a.sort()
        b = max(b, s - sum(a[:j]))
    #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 = V[N - i + j:N]
        s = sum(a)
        #print("s=",s)
        a.sort()
        b = max(b, s - sum(a[:j]))
    #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:
#!/usr/bin/env python3
import sys


def solve(N: int, K: int, V: "List[int]"):
    l = [0] * (K + 1)
    r = [0] * (K + 1)
    for i in range(1, K + 1):
        v = V[:i]
        v.sort(reverse=True)
        for j in range(0, i):
            if i + j <= K:
                l[i + j] = max(l[i + j], sum(v[:i - j]))

    V.reverse()
    for i in range(1, K + 1):
        v = V[:i]
        v.sort(reverse=True)
        for j in range(0, i):
            if i + j <= K:
                r[i + j] = max(r[i + j], sum(v[:i - j]))

    #print(l)
    #print(r)
    ret = 0
    for i in range(0, len(l)):
        #print(l[i], r[K - i - 2])
        ret = max(ret, l[i] + r[K - i])

    tmp = 0
    for v in V:
        if v > 0:
            tmp += v
    ret = min(ret, tmp)
    print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    V = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    solve(N, K, V)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split(" "))
Values = list(map(int, input().split(" ")))
maxS = 0
for garbage in range((K+1)//2):
    for i in range(K-garbage+1):
        catch = Values[0:K-garbage-i] + Values[N-i:N]
        S = sum(catch)
        catch = sorted(catch)
        tmp = garbage
        for c in catch:
            if tmp == 0 or c >= 0:
                break
            S -= c
            tmp -= 1
        maxS = max(S, maxS)
print(maxS)

Submission status: Wrong Answer

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

ans = 0
for x in range(1, K):
    for i in range(x+1):
        Ts = Vs[:i] + Vs[N-(x-i):]
        sumOut = sum(Ts)
        Ts.sort()

        for T in Ts[:K-x]:
            if T < 0:
                sumOut -= T
            else:
                break

        ans = max(ans, sumOut)

print(ans)

Submission status: Wrong Answer

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

ans = 0
for push_num in range(K // 2 + 1):
    gem_num = K - push_num
    # print("#", push_num, gem_num)
    if gem_num >= N:
        gem_list = list(V)
        # print("##", gem_list)
        gem_list.sort()
        ans_tmp = sum(gem_list[push_num:])
        if ans < ans_tmp: ans = ans_tmp
        continue
    else:
        for l_num in range(gem_num + 1):
            r_num = gem_num - l_num
            gem_list = []
            for i in range(l_num): gem_list.append(V[i])
            for i in range(r_num): gem_list.append(V[-(r_num - i)])
            # print("##", gem_list)
            gem_list.sort()
            ans_tmp = sum(gem_list[push_num:])
            if ans < ans_tmp: ans = ans_tmp

print(ans)

Submission status: Wrong Answer

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

sV=sorted(V)
ans=0
for i in range(N):
  for j in range(N-i):
    if i+j<=K:
      if i+j>=N:
        L=sV
      else:
        L=V[:i]+V[N-j:]
        L.sort()
      k=bisect.bisect_right(L,0)
      kans=sum(L[min(K-i-j,k):])
      ans=max(ans,kans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
# gcd
from fractions import gcd
# 切り上げ，切り捨て
# from math import ceil, floor
# リストの真のコピー（変更が伝播しない）
# from copy import deepcopy
# 累積和。list(accumulate(A))としてAの累積和
from itertools import accumulate
# l = ['a', 'b', 'b', 'c', 'b', 'a', 'c', 'c', 'b', 'c', 'b', 'a']
# S = Counter(l)  # カウンタークラスが作られる。S=Counter({'b': 5, 'c': 4, 'a': 3})
# print(S.most_common(2))  # [('b', 5), ('c', 4)]
# print(S.keys())  # dict_keys(['a', 'b', 'c'])
# print(S.values())  # dict_values([3, 5, 4])
# print(S.items())  # dict_items([('a', 3), ('b', 5), ('c', 4)])
from collections import deque
# import math
# from functools import reduce
#
# input関係の定義
# fin = open('in_1.txt', 'r')
# sys.stdin = fin
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().rstrip().split())
def lmi(): return list(map(int, input().rstrip().split()))
def li(): return list(input().rstrip())
# template


def iterate_tokens():
    for line in sys.stdin:
        for word in line.split():
            yield word


if __name__ == '__main__':

    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    V = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"

    # write code
    left = [-10 ** 9] * (K+10)
    right = [-10 ** 9] * (K + 10)
    left[0] = 0
    right[0] = 0
    left[1] = V[0]
    right[1] = V[-1]
    for i in range(2, K+1):
        tmp_max = 0
        for j in range(i // 2, i):
            tmp_V = V[:j]
            tmp_V.sort()
            if tmp_max < sum(tmp_V[i - 2 * j:]):
                tmp_max = sum(tmp_V[i - 2 * j:])
        # print(tmp_max)
        left[i] = tmp_max

    for i in range(2, K+1):
        tmp_max = 0
        for j in range(i // 2, i):
            tmp_V = V[-j:]
            tmp_V.sort()
            if tmp_max < sum(tmp_V[i - 2 * j:]):
                tmp_max = sum(tmp_V[i - 2 * j:])
        # print(tmp_max)
        right[i] = tmp_max
    tmp_ans = -10 ** 9
    # print(left)
    # print(right)
    for i in range(K+1):
        if tmp_ans < left[i] + right[K - i]:
            tmp_ans = left[i] + right[K - i]
    print(tmp_ans)

Submission status: Wrong Answer

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

maxv = 0
# r: 返す回数
for r in range(k // 2 + 1):
    t = k - r  # 取る回数
    g = t - r  # 手元に残る個数
    if g > n:
        continue

    if t >= n:
        vss = sorted(vs, reverse=True)
        maxv = max(maxv, sum(vss[:g]))
    else:
        for il in range(t+1):
            ir = t - il
            vss = vs[:il] if ir == 0 else vs[:il] + vs[-ir:]
            vss = sorted(vss, reverse=True)
            maxv = max(maxv, sum(vss[:g]))

print(maxv)

Submission status: Wrong Answer

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

ans = 0
for l_pop in range(K + 1):
    for r_pop in range(K + 1):
        X = []
        if l_pop + r_pop > K:
            continue
        else:
            X.extend(V[:l_pop])
            X.extend(V[::-1][:r_pop])

        X.sort()
        tmp = sum(X)
        for k in range(K - l_pop - r_pop):
            if k > len(X) - 1:
                break
            else:
                if X[k] < 0:
                    tmp -= X[k]

        ans = max(ans, tmp)

print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, K: int, V: "List[int]"):
    l = [0] * (K + 1)
    r = [0] * (K + 1)
    for i in range(1, K + 1):
        v = V[:i]
        v.sort(reverse=True)
        for j in range(0, i):
            if i + j <= K:
                l[i + j] = max(l[i + j], sum(v[:i - j]))

    V.reverse()
    for i in range(1, K + 1):
        v = V[:i]
        v.sort(reverse=True)
        for j in range(0, i):
            if i + j <= K:
                r[i + j] = max(r[i + j], sum(v[:i - j]))

    #print(l)
    #print(r)
    ret = 0
    for i in range(0, len(l)):
        #print(l[i], r[K - i - 2])
        ret = max(ret, l[i] + r[K - i])
    print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    V = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    solve(N, K, V)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

p = min(n, k)

res = 0

for i in range(p, -1, -1):
        # kことる
        for l in range(i + 1):
                r = i - l
                # 左からl, 右からrとる
                q = []
                for w in range(l):
                        q.append(v[w])
                for w in range(n - r, n):
                        q.append(v[w])
                q = sorted(q)
                ans = -10 ** 20
                tmp = sum(q)
                for w in range(min(p - i, len(q))):
                        tmp -= q[w]
                        ans = max(ans, tmp)
                res = max(res, ans)

print(res)

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 = V[:i - j]
        s = sum(a)
        #print("s=",s)
        a.sort()
        b = max(b, s - sum(a[:j]))
    #print("b=",b)
    l.append(b)
#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 = V[N - i + j:]
        s = sum(a)
        #print("s=",s)
        a.sort()
        b = max(b, s - sum(a[:j]))
    #print("b=",b)
    r.append(b)
#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:
N,K = list(map(int, input().split()))
V = list(map(int, input().split()))
#print(N,K,min(N,K))

from itertools import accumulate
Lcumsum = [0] + list(accumulate(V))
Rcumsum = [0] + list(accumulate(V[::-1]))
#print(Lcumsum)
#print(Rcumsum)

ans = -10**9
               
for l in range(min(N,K)):
  for r in range(min(N-l,K-l)):
    Lsum = Lcumsum[l]
    Rsum = Rcumsum[r]
    Nsum = sum(sorted([v for v in (V[:l] + V[N-r:]) if v<0])[:K-l-r])
    ans = max(ans, Lsum+Rsum-Nsum)
    #print(l,r,Lsum,Rsum,Nsum,Lsum+Rsum-Nsum)
    
print(ans)

Submission status: Wrong Answer

Solution code:
#ABC128-D
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(input())
def S(): return list(input())
n,k=IL()
V=IL()
ans=0

for i in range(min(k+1,n+1)):
    
    print("i",i)
    for j in range(i+1):
        t=0
        m=[]
        for l in range(j):
            if V[l]<0:
                m.append(V[l])
            else:
                t+=V[l]
        for l in range(i-j):
            if V[-l-1]<0:
                m.append(V[-l-1])
            else:
                t+=V[-l-1]
        m.sort(reverse=True)
        if len(m)>k-i:
            t+=sum(m[:len(m)-(k-i)])
       
        
        ans=max(ans,t)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,datetime
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())

N,K = inpl()
vv = inpl()

left = [0]
tmp = 0
for i in range(N):
    tmp += vv[i]
    left.append(tmp)

right = [0]
tmp = 0
for i in reversed(range(N)):
    tmp += vv[i]
    right.append(tmp)


ans = 0
for sute in range(K//2+1): #捨てる数
    toru = K - sute
    for lnum in range(toru+1):
        for rnum  in range(toru-lnum+1):
            torukazu = vv[:lnum] + vv[N-rnum:]
            torukazu.sort()
            '''
            ind = bisect.bisect_left(torukazu,0)
            if ind < sute:
                tmpste = ind
            else:
                tmpste = sute
            '''
            tmp = sum(torukazu[sute:])
            ans = max(tmp,ans)

print(ans)

Submission status: Wrong Answer

Solution code:
def getN():
    return int(input())

def getMN():
    return list(map(int, input().split()))

def getlist():
    return list(map(int, input().split()))

n, k = getlist()
gem = getlist()
ans = 0
for i in range(k):
    for l in range(k):
        for r in range(k-l):
            gets = gem[:l] + gem[n-r:]
            gets.sort()
            ret = k-l-r
            tmp = sum(gets)
            #print(gets, ret)
            for g in gets:
                if ret > 0 and g <= 0:
                    tmp -= g
                    ret -= 1
                else:
                    break
            #print(tmp)
            if ans < tmp:
                ans = tmp

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
l = []
for i in range(K + 1): #左に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        #print("j=",j)
        a = V[:i - j]
        s = sum(a)
        #print("s=",s)
        a.sort()
        b = max(b, s - sum(a[:j]))
    #print("b=",b)
    l.append(b)
#print(l)
r = []
for i in range(K + 1): #右に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        #print("j=",j)
        a = V[N - i + j:]
        s = sum(a)
        #print("s=",s)
        a.sort()
        b = max(b, s - sum(a[:j]))
    #print("b=",b)
    r.append(b)
#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:
import bisect


def main():
    N, K = map(int, input().split())
    V = [int(x) for x in input().split()]
    Vr = list(reversed(V))

    ans = -float("inf")
    for l in range(0, K+1):
        for r in range(0, K-l+1):
            n = K - r - l
            if n < 0:
                continue
            a1 = V[:l]
            a2 = Vr[:r]
            a = a1 + a2
                 # + V[-r+1:]  # 取り出し
            # print(f"{l} {r}\t", a)
            a = sorted(a)

            i = bisect.bisect(a, 0)
            a = a[min(i, n):]
            score = sum(a)
            ans = max(ans, score)
            # print(f"score={score}")

    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 = []
for i in range(K + 1): #左に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        #print("j=",j)
        a = V[:i - j]
        s = sum(a)
        #print("s=",s)
        a.sort()
        b = max(b, s - sum(a[:j]))
    #print("b=",b)
    l.append(b)
#print(l)
r = []
for i in range(K + 1): #右に何回操作するか
    #print("i=",i)
    b = 0
    for j in range(i // 2 + 1): #いくつ捨てるか
        #print("j=",j)
        a = V[N - i + j:]
        s = sum(a)
        #print("s=",s)
        a.sort()
        b = max(b, s - sum(a[i:]))
    #print("b=",b)
    r.append(b)
#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:
import heapq

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

max_v = -float('inf')
for a in range(min(k, n)):
    total = 0
    minus = []
    for i in range(a):
        total += vs[i]
        if vs[i] < 0:
            heapq.heappush(minus, vs[i])
    for b in range(min(k-a, n-a)):
        c = k - a - b
        if c < 0:
            break
        h = minus[:]
        t = total
        for i in range(b):
            t += vs[n-1-i]
            if vs[n-1-i] < 0:
                heapq.heappush(h, vs[n-1-i])
        for i in range(c):
            if h:
                v = heapq.heappop(h)
                t -= v
        max_v = max(max_v, t)

print(max_v)

Submission status: Wrong Answer

Solution code:

def main():
    buf = input()
    buflist = buf.split()
    N = int(buflist[0])
    K = int(buflist[1])
    buf = input()
    buflist = buf.split()
    V = list(map(int, buflist))
    max_value = 0
    for i in range(min(N, K+1)):
        push_limit = K - i
        for j in range(i+1):
            jewel = []
            for k in range(-i+j, j):
                jewel.append(V[k])
            jewel = list(sorted(jewel))
            value = sum(jewel)
            for k in range(push_limit):
                if k >= len(jewel):
                    break
                if jewel[k] < 0:
                    value += -jewel[k]
                else:
                    break
            if value > max_value:
                max_value = value
    print(max_value)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
v = list(map(int, input().split()))
ret = 0
for l in range(k + 1):
    for r in range(k - l):
        d = k - l - r
        g = sorted(v[:l] + v[n - r:])
        for i in range(min(d, len(g))):
            g[i] = max(0, g[i])
        ret = max(ret, sum(g))
print(ret)

Submission status: Wrong Answer

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

V = [int(x) for x in input().split()]

ans = 0
for a in range(K+1):
    for b in range(K+1):
        max_CD = min(a + b, min(2*N, K) - (a+b))
        if max_CD < 0 or a + b >= N:
            break
        vs = V[:a] + V[N-b:]
        vs.sort()
        i = bisect.bisect_left(vs, 0)
        #print(a, b, max_CD, vs, i)
        ans = max(ans, sum(vs[min(i, max_CD):]))
print(ans)

Submission status: Wrong Answer

Solution code:
# まず取り出しきっちゃってから捨てる
# 左右からいくつずつ取り出すか

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

max_value = 0 # 何もとらない

for L in range(N):
  for R in range(N):
    if L+R > K:
      break
    if L+R > N:
      break
    #get = V[:L] + V[-R:]
    get = V[:L]
    if R > 0:
      get += V[-R:]
    get.sort()
    rest = K - (L+R)
    minus = sum((1 if x < 0 else 0 for x in get))
    if minus > rest:
      value = sum(get[rest:])
    else:
      value = sum((x for x in get if x > 0))
    if value > max_value:
      max_value = value
    #print(L,R,rest,get,value)
      
      
   
print(max_value)

Submission status: Wrong Answer

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

ans = 0
for l in range(K+1):
  for r in range(K+1):
    if l+r<=K:
      T = V[:l]+(V[-r:] if r>0 else [])
      T = sorted(T)[::-1]
      for _ in range(K-l-r):
        if len(T)>0 and T[-1]<0:
          T.pop()
      ans = max(ans, sum(T))
print ans

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
from collections import defaultdict
import math
sys.setrecursionlimit(20000000)
#input = sys.stdin.readline

n,k = map(int,input().split())
v = list(map(int,input().split()))
ans = 0
for i in range(k):
        for j in range(k-i+1):
                x = v[:i]
                if n< i+j:
                        continue
                if j > 0:
                        x = x + v[-j:]
                x.sort(key=lambda x : -x)
                kai = i+ j
                while kai < k and x and x[-1] < 0:
                        x.pop()
                        kai+=1
                ans = max(ans,sum(x))
print(ans)