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 sys

readline = sys.stdin.readline

N, K = map(int, readline().split())

V = list(map(int, readline().split()))



max_total = -10 ** 8

for npop in range(0, min(N, K) + 1):
    push_start = 0 if (K - npop) % 2 == 0 else 1
    
    for npush in range(push_start, min(K - npop, npop) + 1, 2):
        for n_left_pop in range(npop + 1): # N
            n_right_pop = npop - n_left_pop

            taken = V[:n_left_pop] + ([] if n_right_pop == 0 else V[-n_right_pop:])
            taken.sort()

            _total = sum(taken[npush:])
            max_total = max(max_total, _total)

print(max_total)

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
D=list(map(int,input().split(" ")))
answer=-99999999999

for i in range(m+1):
    take=i
    trash=m-i
    for j in range(take+1):
        if j>=n:
            goukei=D
        else:
            left=j
            right=j-take
            leftjewel=D[:left]
            rightjewel=D[right:]
            if right==0:
                rightjewel=[]
            goukei=leftjewel+rightjewel
        goukei.sort()
        for i in range(trash):
            if goukei!=[]:
                if goukei[0]<0:
                    del goukei[0]
        if sum(goukei)>answer:
            answer=sum(goukei)
print(answer)

Submission status: Wrong Answer

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

mi = lambda: map(int, input().split())
li = lambda: list(map(int, input().split()))

N, K = mi()
V = li()

RV = {0: {'v':0,'j':[]}}
LV = {0: {'v':0,'j':[]}}
available_v = [0]

for i in range(1,min([K,N])):
  lv = sum(V[:i])
  LV[i] = {'v': lv, 'j': V[:i]}
  rv = sum(V[-i:])
  RV[i] = {'v': sum(V[-i:]), 'j': V[-i:]}
  available_v += [lv, rv]

for i in range(min([K,N])):
  for j in range(min([K-i,N-i])):
    available_v.append(LV[i]['v'] + RV[j]['v'])
    jv = sorted(LV[i]['j'] + RV[j]['j'])
    if K - i - j < len(jv):
      available_v.append(sum(jv[K-i-j:]))

print(max(available_v))

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
ans=0
KK=K
if K>N:
    KK=N
for i in range(KK+1):
    j=KK-i
    a=V[:i]
    b=V[N-j:]
    ans=max(ans,sum(a)+sum(b))
    k=sum(a)+sum(b)
    c=a+b
    c.sort(reverse=True)
    W=K+max(0,K-KK)
    W-=2
    while(W>0):
        if c==[]:
            break
        t=c.pop()
        if t in a:
            a.remove(t)
        elif t in b:
            b.remove(t)
        else:
            print("W")
            quit()
        if a!=[] and b!=[] :
            if a[-1]<=b[0]:
                h=a.pop(-1)
            else:
                h=b.pop(0)
        elif a!=[] and b==[]:
            h=a.pop(-1)
        elif b!=[] and a==[]:
            h=b.pop(0)
        else:
            break
        c.remove(h)
        k=k-t-h
        ans=max(k,ans)
        W-=2
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
v = list(map(int, input().split()))
import copy
originalV = copy.deepcopy(v)
gyakuv = v[::-1]
ans = 0
for i in range(k + 1): #i個使う
    if i >= n:
        break
    this = []
    for j in range(i): #右からj個使う左からi - j // n > iの時
        #print(i)
        this = v[:j + 1] + gyakuv[:min(max(i - j - 1, 0), n - j - 1)]
        #print(this, j, i)
        tmp = sum(this)
        this.sort()
        for asd in range(min(k - i, len(this))):
            #print(i)
            if this[asd] >= 0:
                break
            tmp -= this[asd]

        ans = max(tmp, ans)


print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int, input().strip().split(' '))
V = list(map(int, input().strip().split(' ')))
V += V
# まず宝石をi個取る、その後j個返す
# i個の取り方はi+1通り
# 返す時は負のもののみ、絶対値が大きいtopj個を返すので、取り方が決まるとそのときの最大点はすぐ決まる
# 0 <= i <= K, 0 <= j <= K-i
now_max = 0
for i in range(1, min(K+1, N)):
  for offset in range(i+1):
    jewel = sorted(V[-offset+N: -offset+i+N])
    remain_del = K-i
    while True:
      if len(jewel) == 0 or remain_del == 0 or jewel[0] > 0:
        break
      jewel.pop(0)
      remain_del -= 1
    now_max = max(now_max, sum(jewel))
print(now_max)

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 = 0
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()
        tmp = cum[n] - (cum[j+1] - cum[i])
        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
ans = max([ans, v[0], v[-1]])
if k >= 2 and n >= 2:
    ans = max([ans, v[1], v[-2]])
print(ans)

Submission status: Wrong Answer

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

# 左からleft個、右からright個、返すのをret個とする。

result = 0
for left in range(max(N,K)+1):
    for right in range(max(K-left, N)+1):
        ll = V[0:left]
        rr = list(collections.deque(V, right))
        total = sorted(ll + rr)
        for ret in range(min(K-left-right, len(total))+1):
            res = list(collections.deque(total, len(total) - ret))
            #print("----", left, right, ret)
            if result <= sum(res):
                result = sum(res)

print(result)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
ans=0
KK=K
if K>N:
    KK=N
for i in range(KK+1):
    j=KK-i
    a=V[:i]
    b=V[N-j:]
    ans=max(ans,sum(a)+sum(b))
    k=sum(a)+sum(b)
    c=a+b
    c.sort(reverse=True)
    W=K
    W-=2
    while(W>0):
        if c==[]:
            break
        t=c.pop()
        if t in a:
            a.remove(t)
        elif t in b:
            b.remove(t)
        else:
            print("W")
            quit()
        if a!=[] and b!=[] :
            if a[-1]<=b[0]:
                h=a.pop(-1)
            else:
                h=b.pop(0)
        elif a!=[] and b==[]:
            h=a.pop(-1)
        elif b!=[] and a==[]:
            h=b.pop(0)
        else:
            break
        c.remove(h)
        k=k-t-h
        ans=max(k,ans)
        W-=2
print(ans)

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l():
	return list(map(int,input().split()))
def m():
	return map(int,input().split())
def s(x):
	a = []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa == x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x):
	return " ".join(map(str,x))

n,m = m()

a = l()

su = 0
for i in range(n):
	ll = max(i,n-(m - i))
	for j in range(ll,n+1):
		q = []
		co = 0
		p = a[:i]
		pp = a[j:]
		for k in range(len(p)):
			if p[k] < 0:
				q.append(p[k])
		for k in range(len(pp)):
			if pp[k] < 0:
				q.append(pp[k])
		co += sum(p)
		co += sum(pp)
		q.sort()
		for k in range(min(len(q),j-ll)):
			co += abs(q[k])
		su = max(su,co)
print(su)

Submission status: Wrong Answer

Solution code:
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

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

if N == 1:
    print(max(0,V[0]))
    exit()

ans = -mod
for i in range(K): # 戻す数
    for j in range(K-i+1):
        if j < N-(K-i-j):
            ans_list = V[:j]+V[N-(K-i-j):]
            ans_list.sort()
            tmp = sum(ans_list)
            for k in range(min(len(ans_list),i)):
                if ans_list[k] < 0:
                    tmp -= ans_list[k]
            ans = max(ans,tmp)
        else:
            pass

print(max(ans,0))

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):
#左
  tmp = sum(V[:i])
  if ans < tmp:
    ans = tmp
  tmp = sorted(V[:i])
  for j in range(K-i+1):
    tmp_ = sum(tmp[j:])
    if ans < tmp_:
      ans = tmp_
#右
  tmp = sum(V[N-i:])
  if ans < tmp:
    ans = tmp
  tmp = sorted(V[N-i:])
  for j in range(K-i+1):
    tmp_ = sum(tmp[j:])
    if ans < tmp_:
      ans = tmp_
#両方
  for k in range(i):
    if N-k+1 != N:
      tmp = V[:k]+V[N-k+1:]
      tmp_ = sum(tmp)
      if ans < tmp_:
        ans = tmp_
      tmp = sorted(tmp)
      for j in range(K-k):
        tmp_ = sum(tmp[j:])
        if ans < tmp_:
          ans = tmp_
print(ans)

Submission status: Wrong Answer

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

def region(V, k):
    l = len(V)
    return [V[0:i] + V[l-k+i:] for i in range(k+1)]

def choice(region, K):
    te = len(region)
#    print("-----------")
#    print("te = ", te)
#    print(region)
#    print(sorted(region)[K-te:])
#    print("-----------")
    return sum(sorted(region)[K-te:])

print(max([choice(r, K) for k in range(1, K+1) for r in region(V, k)]))

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(min(K+1, N)):
        for take_left in range(take_count+1):
            # if take_left > N: break
            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]
            # print(took)
            maximum = max(maximum, sum(took))

    print(maximum)

main()

Submission status: Wrong Answer

Solution code:
import sys

readline = sys.stdin.readline

N, K = map(int, readline().split())

V = list(map(int, readline().split()))



max_total = -10 ** 8

for npop in range(0, min(N, K) + 1):
    push_start = 0 if (K - npop) % 2 == 0 else 1
    
    for npush in range(push_start, min(K - npop, npop) + 1):
        for n_left_pop in range(npop + 1): # N
            n_right_pop = npop - n_left_pop

            taken = V[:n_left_pop] + ([] if n_right_pop == 0 else V[-n_right_pop:])
            taken.sort()

            _total = sum(taken[npush:])
            max_total = max(max_total, _total)

print(max_total)

Submission status: Wrong Answer

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

def rec(left, right, k, minus) :
    if k == 0 or left >= right :
        return 0

    if V[left] < 0 :
        a = rec(left+1, right, k-1, minus+[V[left]]) + V[left]
    else :
        a = rec(left+1, right, k-1, minus) + V[left]

    if V[right] < 0 :
        b = rec(left, right-1, k-1, minus+[V[right]]) + V[right]
    else :
        b = rec(left, right-1, k-1, minus) + V[right]

    c = 0
    if k <= len(minus) :
        minus.sort()
        c = rec(left, right, k-1, minus[1:]) - minus[0]

    return max(a, b, c, 0)

print(rec(0, N-1, K, []))

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 = 0
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()
        tmp = cum[n] - (cum[j+1] - cum[i])
        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
ans = max([ans, v[0], v[-1]])
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
import heapq
from collections.abc import Iterable
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(N: int, K: int, V: "List[int]"):

    lq = []
    acc_l = 0
    ret = 0
    for li in range(min(N, K + 1)):
        if 0 < li:
            acc_l += V[li - 1]
            heapq.heappush(lq, V[li - 1])

        acc_r = 0
        rq = [v for v in lq]
        heapq.heapify(rq)
        for _ri in range(min(N, K + 1) - li):
            if 0 < _ri:
                ri = N - _ri
                acc_r += V[ri]
                heapq.heappush(rq, V[ri])

            acc_c = 0
            ci = K - li - _ri
            tmp_q = [v for v in rq]
            while (0 < ci) and (0 < len(tmp_q)):
                tmp_v = heapq.heappop(tmp_q)
                if 0 <= tmp_v:
                    break
                acc_c += tmp_v
                ci -= 1

            acc = acc_r + acc_l - acc_c
            if ret < acc:
                ret = acc
    return ret


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]"
    result = solve(N, K, V)
    if isinstance(result, Iterable) and not isinstance(result, str):
        result = '\n'.join([str(v) for v in result])
    print(result)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque, OrderedDict
from copy import deepcopy
from fractions import gcd
from functools import lru_cache, reduce
from math import ceil, floor
from sys import setrecursionlimit

import heapq as hq
import itertools as its
import operator as op


# globals
inf = float('inf')
N = 0


def set_inputs():
    global N
    return


def main():
    setrecursionlimit(100000)
    set_inputs()
    # ----------MAIN----------
    n, k = get_li()
    V = get_li()
    ans = 0
    for v in range(k):
        forward = V[:v]
        backward = V[n-1:n-(k-v)-1:-1]
        tmp = sum(forward + backward)
        while True:
            minf = min(forward + [inf])
            minb = min(backward + [inf])
            if min(minf, minb) >= 0:
                break
            last = inf
            if len(forward) > 0:
                last = forward[-1]
            if len(backward) > 0:
                last = min(last, backward[-1])
            if last >= 0 and abs(min(minf, minb)) < last:
                break
            if minf < minb:
                i = forward.index(minf)
                if i == len(forward) - 1:
                    forward.pop(i)
                elif len(backward) == 0:
                    forward.pop(i)
                    forward.pop()
                elif forward[-1] < backward[-1]:
                    forward.pop(i)
                    forward.pop()
                else:
                    forward.pop(i)
                    backward.pop()
            else:
                i = backward.index(minb)
                if i == len(backward) - 1:
                    backward.pop(i)
                elif len(forward) == 0:
                    backward.pop(i)
                    backward.pop()
                elif backward[-1] < forward[-1]:
                    backward.pop(i)
                    backward.pop()
                else:
                    backward.pop(i)
                    forward.pop()
            tmp = sum(forward + backward)
        ans = max(ans, tmp)
    print(ans)
    return


def get_int():
    return int(input())


def get_float():
    return float(input())


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


def get_li():
    return [int(i) for i in input().split()]


def get_lf():
    return [float(f) for f in input().split()]


def get_lc():
    return list(input().strip())


def get_data(n, types, sep=None):
    if len(types) == 1:
        return [types[0](input().strip()) for _ in range(n)]
    return list(zip(*(
        [t(x) for t, x in zip(types, input().strip().split(sep=sep))]
        for _ in range(n)
    )))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
res = 0
if N * 2 <= K:
    for v in range(N):
        if v >= 0:
            res += v
    print(res)
    exit()
elif N <= K < N * 2:
    V.sort(reverse = True)
    if K % 2 == 0:
        for i in range(K // 2 - 1):
            if V[i*2] + V[i*2+1] > 0:
                res += V[i*2] + V[i*2+1]
    else:
        res += V[0]
        for i in range(K // 2 - 1):
            if V[i*2+1] + V[i*2+2] > 0:
                res += V[i*2+1] + V[i*2+2]
    print(res)
    exit()
else:
    for i in range(K+1):
        ans = 0
        if i != K :
            Vsub = sorted(V[:i] + V[-K+i:], reverse = True)
        else:
            Vsub = sorted(V[:i], reverse = True)
        if K % 2 == 0:
            for i in range(K // 2 - 1):
                if Vsub[i*2] + Vsub[i*2+1] > 0:
                    ans += Vsub[i*2] + Vsub[i*2+1]
        else:
            ans += V[0]
            for i in range(K // 2 - 1):
                if Vsub[i*2+1] + Vsub[i*2+2] > 0:
                    ans += Vsub[i*2+1] + Vsub[i*2+2]
        res = max(ans, res)
print(res)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

V = [int(x) for x in input().split()]
ans = 0
for i in range(K+1):
    for r in range(i):
        for l in range(i-r):
            n =sorted(V[0:r]+V[N-1:])
            if len(n) <=K-i+1: 
                for j in range(len(n)):
                    if n[j]>0:
                        break
                ans = max(ans,sum(n[j:]))
            elif n[K-i+1] < 0:
                ans = max(ans,sum(n[K-i+2:]))
            else:
                for j in range(K-i):
                    if n[j]>0:
                        break
                ans = max(ans,sum(n[j:]))
#            print(n[K-i+2:],sum(n[K-i+2:]))
#                print(r,l,ri,i-r-l-ri-1,sorted(V[0:r])[ri:],sorted(V[N-l:])[i - r - l- ri-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 + 1):
    count = K - i
    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
            # print(temp, sum(temp))
            sumv = sum(temp)
            left -= 1
            right += 1
            if sumv > maxv:
                maxv = sumv

print(maxv)

Submission status: Wrong Answer

Solution code:
a,b = map(int,input().split())
A=list(map(int,input().split()))

output=0
#for tr in range(b//2+1):
for tr in range(b):
    for g in range(b-tr+1):
        #print(g)
        tmparr1=[]
        tmparr1.extend(A[:g])
        if g-b+tr<0:
            tmparr1.extend(A[g-b+tr:])
        #print(tmparr1)
        tmparr1.sort()
        #print(tmparr1)
        #print(tmparr1[tr:])

        #trまで捨てれる
        if output<sum(tmparr1[tr:]):
            output=sum(tmparr1[tr:])

        for t in range(tr):
            if output<sum(tmparr1[t:]) :
                output=sum(tmparr1[t:])
            #print(output)
print(output)

Submission status: Wrong Answer

Solution code:
import itertools
import numpy as np
n, k = map(int, input().split())
s_list = list(map(int, input().split()))
h_list = []
res_list = [0]

def rec_ope(s_list, h_list, k, minus_len, task=""):
  if k == 0:
    res_list.append(sum(h_list))
    return 0
  if len(h_list) > 0:
    if minus_len <= k:
      tmp_h = h_list.copy()
      min_h = min(h_list)
      tmp_h.remove(min_h)
      tmp_s = s_list.copy()
      tmp_s.insert(0, min_h)
      if task != "C":
      	rec_ope(tmp_s, tmp_h, k-1, minus_len-1, "A")
      tmp_s = s_list.copy()
      tmp_s.append(min_h)
      if task != "D":
      	rec_ope(tmp_s, tmp_h, k-1, minus_len-1, "B")
  if len(s_list) > 0:
    tmp_h = h_list.copy()
    tmp_s = s_list.copy()
    add_s = tmp_s.pop(0)
    tmp_h.append(add_s)
    if add_s < 0:
      minus_len += 1
    if task != "A":
      rec_ope(tmp_s, tmp_h, k-1, minus_len, "C")
    tmp_h = h_list.copy()
    tmp_s = s_list.copy()
    add_s = tmp_s.pop(-1)
    tmp_h.append(add_s)
    if add_s < 0:
      minus_len += 1
    if task != "B":
      rec_ope(tmp_s, tmp_h, k-1, minus_len, "D")

rec_ope(s_list, h_list, k, 0)
print(max(res_list))

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l():
	return list(map(int,input().split()))
def m():
	return map(int,input().split())
def s(x):
	a = []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa == x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x):
	return " ".join(map(str,x))

n,m = m()

a = l()

su = 0
for i in range(n):
	ll = max(i,n-(m - i))
	for j in range(ll,n+1):
		q = []
		co = 0
		p = a[:i]
		pp = a[j:]
		print(p,pp)
		for k in range(len(p)):
			if p[k] < 0:
				q.append(p[k])
		for k in range(len(pp)):
			if pp[k] < 0:
				q.append(pp[k])
		co += sum(p)
		co += sum(pp)
		q.sort()
		for k in range(min(len(q),j-ll)):
			co += abs(q[k])
		print(co)
		su = max(su,co)
print(su)

Submission status: Wrong Answer

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
ans=0
KK=K
if K>N:
    KK=N
for i in range(KK+1):
    j=KK-i
    a=V[:i]
    b=V[N-j:]
    ans=max(ans,sum(a)+sum(b))
    k=sum(a)+sum(b)
    c=a+b
    c.sort(reverse=True)
    W=K
    W-=2
    while(W>0):
        if c==[]:
            break
        t=c.pop()
        if t in a:
            a.remove(t)
        elif t in b:
            b.remove(t)
        else:
            print("W")
            quit()
        if a!=[] and b!=[] :
            if a[-1]<=b[0]:
                h=a.pop(-1)
            else:
                h=b.pop(0)
        elif a!=[] and b==[]:
            h=a.pop(-1)
        elif b!=[] and a==[]:
            h=b.pop(0)
        else:
            break
        k=k-t-h
        ans=max(k,ans)
        W-=2
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun May 26 20:56:05 2019

@author: Yamazaki Kenichi
"""
import heapq

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

if N < K:
    K = N

ans = 0
for i in range(K):
    for j in range(K-i+1):
        tmp = 0
        minus = [0]
        for k in range(K-i):
            tmp += V[k-j]
            heapq.heappush(minus,V[k-j])
#            print(tmp,minus)
        tmp += (-sum(minus[:i]))
#        print(ans,tmp,i,j,k)
        ans = max(ans,tmp)
    
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

N, K = tuple([int(x) for x in input().split(' ')])
V = [int(x) for x in input().split(' ')]
# V = np.array(V)

ans = 0
for i in range(K):
    for j in range(K-i):
        tmp = V[:(i+1)] + V[(N-j):]
        tmp.sort()
        for k, t in enumerate(tmp):
            if t>=0 or k+2 > K-i-j:
                ans = max(sum(tmp[k:]), ans)  
                break

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
res = 0
if N * 2 <= K:
    for v in range(N):
        if v >= 0:
            res += v
    print(res)
    exit()
elif N <= K < N * 2:
    V.sort(reverse = True)
    if K % 2 == 0:
        for i in range(K // 2 - 1):
            if V[i*2] + V[i*2+1] > 0:
                res += V[i*2] + V[i*2+1]
    else:
        res += V[0]
        for i in range(K // 2 - 1):
            if V[i*2+1] + V[i*2+2] > 0:
                res += V[i*2+1] + V[i*2+2]
    print(res)
    exit()
else:
    for i in range(K+1):
        ans = 0
        if i != K :
            Vsub = sorted(V[:i] + V[-K+i:], reverse = True)
        else:
            Vsub = sorted(V[:i], reverse = True)
        print(Vsub)
        if K % 2 == 0:
            for i in range(K // 2 - 1):
                if Vsub[i*2] + Vsub[i*2+1] > 0:
                    ans += Vsub[i*2] + Vsub[i*2+1]
        else:
            ans += V[0]
            for i in range(K // 2 - 1):
                if Vsub[i*2+1] + Vsub[i*2+2] > 0:
                    ans += Vsub[i*2+1] + Vsub[i*2+2]
        res = max(ans, res)
print(res)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
v = list(map(int, input().split()))
maxvalue = 0
for l in range(n+1):
    for r in range(l+1, n+1):
        ava = sorted(v[:l] + v[r:])
        takeop = len(ava)
        if takeop <= k:
            value = sum(ava)
            for i in range(min(takeop, k - takeop)):
                if ava[i] >= 0:
                    break
                else:
                    value -= ava[i]
            maxvalue = max(maxvalue, value)
print(maxvalue)

Submission status: Wrong Answer

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

for i in range(k+1):
  for j in range(k-i+1):
    S=[0]+L[:i]+L[a-j:]
    S.sort()
    x=0
    while x < k-(j+i):
      if S[x]>=0:
        break
      x+=1
    ans=max(ans,sum(S)-sum(S[:x]))
    
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
import heapq
from collections.abc import Iterable
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(N: int, K: int, V: "List[int]"):

    lq = []
    acc_l = 0
    acc_ml = []
    ret = 0
    for li in range(min(N, K + 1)):
        if 0 < li:
            acc_l += V[li - 1]
            if V[li - 1] < 0:
                acc_ml.append(V[li - 1] )

        acc_r = 0
        ms = [v for v in acc_ml]
        ms.sort()
        for _ri in range(min(N, K + 1) - li):
            if 0 < _ri:
                ri = N - _ri
                acc_r += V[ri]
                if V[ri] < 0:
                    ms.append(V[ri])
                    ms.sort()
            ci = min(len(ms), K - li - _ri)
            acc_c = sum(ms[:ci])
            acc = acc_l + acc_r - acc_c
            if ret < acc:
                ret = acc
    return ret


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]"
    result = solve(N, K, V)
    if isinstance(result, Iterable) and not isinstance(result, str):
        result = '\n'.join([str(v) for v in result])
    print(result)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

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


ans = -mod
for i in range(K): # 戻す数
    for j in range(K-i+1):
        if j < N-(K-i-j):
            ans_list = V[:j]+V[N-(K-i-j):]
            ans_list.sort()
            tmp = sum(ans_list)
            for k in range(min(len(ans_list),i)):
                if ans_list[k] < 0:
                    tmp -= ans_list[k]
            ans = max(ans,tmp)
        else:
            pass


print(ans)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
lis = list(map(int,input().split()))
ans = 0
now = 0
for i in range(k+1):
  ri = i
  le = k-i
  r = -1
  l = 0
  now = 0
  while ri > 0 and abs(r) <= n:
    if lis[r] >= 0:
      ri -= 1
      now += lis[r]
      r -= 1
    else:
      ri -= 2
      if ri > 0:
        r -= 1
  while le > 0 and le <= n-abs(r):
    if lis[l] >= 0:
      le -= 1
      now += lis[l]
      l += 1
    else:
      le -= 2
      l += 1
  ans = max(ans,now)
print(ans)