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:
n, k = map(int, input().split())
v = list(map(int, input().split()))
ans = []
for i in range(k):
    p = []
    for j in range(k-i+1):
        left = v[:j]
        if j != k-i:
            right = v[-k+i+j:]
        else:
            right = []
        poyo = left + right
        mo = sum(poyo)
        for z in range(i):
            if poyo:
                mo -= poyo.pop(poyo.index(min(poyo)))
        p.append(mo)
    ans.append(max(p))

k = k - 1
for i in range(k):
    p = []
    for j in range(k-i+1):
        left = v[:j]
        if j != k-i:
            right = v[-k+i+j:]
        else:
            right = []
        poyo = left + right
        mo = sum(poyo)
        for z in range(i):
            if poyo:
                mo -= poyo.pop(poyo.index(min(poyo)))
        p.append(mo)
    ans.append(max(p))

print(max(ans))

Submission status: Wrong Answer

Solution code:
N,K=map(int, input().split())
V=list(map(int, input().split()))
ans=0
from heapq import heapify,heappop
for j in range(1,min(N,K)+1):
    for k in range(j+1):
        x=V[:k]+V[N-j+k:]
        heapify(x)
        b=K-j
        if x[0]<0 and b>0:
            heappop(x)
            b-=1
        ans=max(ans,sum(x))
print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop, heapify

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

# N jewels in dequeue D
# at most K operations
# 1 <= N <= 50
# 1 <= K <= 100
# -10000000 <= Vi <= 10000000

# Operation A, B: Remove left or right
# Operation C, D: Add to left or right

S = 0
for take in range(K + 1):
    for takeL in range(take + 1):
        for takeR in range(take - takeL + 1):
            hand = []
            for i in range(takeL):
                if i >= len(V):
                    break
                heappush(hand, V[i])
            for i in range(takeR):
                if N - i - 1 < 0:
                    break
                heappush(hand, V[N- i - 1])
            s = sum(hand)
            S = max(s, S)
            for i in range(K - take):
                if not hand:
                    break
                heappop(hand)
                s = sum(hand)
                S = max(s, S)
print(S)

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(51, k + 1)):
    at = k - backn

    t = min(n, at)
    # print('----', backn, t)
    for shift in range(t + 1):
        p = v[:t - shift] + v[n - shift:]
        # print(v[:t - shift], v[n - shift:])
        p.sort()
        value = sum(p[backn:])
        results.append(value)
print(max(results))

Submission status: Wrong Answer

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

class Deq:
    def __init__(self, array_):
        self.q = array_
        
    def A(self):
        return self.q.pop(0)

    def B(self):
        return self.q.pop(-1)
    
    def C(self,v):
        self.q = [v] + self.q
        return 0

    def D(self,v):
        self.q += [v]
        return 0
        
deq_v = []
deq = Deq(deq_)
print(deq.q)
method_list = ['A','B','C','D']
for _ in range(K):
  if deq.q[0] > deq.q[-1] and deq.q[0]>0:
    deq_v.append(deq.A())
  elif deq.q[0] < deq.q[-1] and deq.q[-1]>0:
    deq_v.append(deq.B())
  print(deq.q)
	    
print(sum(deq_v))

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].copy()
    if R > 0:
      get += V[-R:].copy()
    get.sort()
    rest = K - (L+R)
    minus = 0
    for x in get:
      if x < 0:
        minus += 1
    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:
# -*- coding: utf-8 -*-
n, k= map(int, input().split())
v= list(map(int, input().split()))
sum_max = 0
for t in range(min(2*n+1, k+1)):
  if t > 0:
    for put in range(t//2 + 1):
      pick = t - put
      for left in range(pick+1):
        right= pick - left
        if left!=0:
          vs=v[0:left]
        else:
          vs=[]
        if right!=0:
          vs.extend(v[-right:])
        vs.sort()
        for i in range(put):
          if vs !=[]:
            if vs[0] < 0:
              del vs[0]
            else:
              break
          else:
            break
        sum_max = max(sum_max, sum(vs))
print(sum_max)

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
u = min(k, n)
for i in range(u + 1):
    tmp = func(i, 0) + func(u - i, 1)
    ans = max(ans, tmp)
    # print(i, u - i, func(i, 0), func(u - i, 1))
print(ans)

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):
    if b-tr+1>a+1:
        aaa=a+1
    else:
        aaa=b-tr+1
    for g in range(aaa):
    #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:
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(-1, 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))):
            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().split())
V = [0]+list(map(int,input().split()))+[0]
S = [0]
for v in V[1:-1]:
    S.append(S[-1]+v)

ans = 0
leftminus = []
leftm = 0
for left in range(min(n+1,k)):
    if V[left] < 0:
        leftminus.append(V[left])
        leftm += 1
    for right in range(n+1,left,-1):
        rightminus = []
        tempans = S[left]
        times = left + n - right + 1
        rm = leftm
        if times > k:
            break
        for v in V[right:]:
            tempans += v
            if v < 0:
                rightminus.append(v)
                rm += 1
        minus = rightminus+leftminus
        minus.sort()
        for j in range(min(k-times,rm)):
            tempans -= minus[j]
        if ans < tempans:
            ans = tempans
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].copy()
    if R > 0:
      get += V[-R:].copy()
    get.sort()
    rest = K - (L+R)
    minus = 0
    for x in get:
      if x < 0:
        minus += 1
    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:


def get_data(data_left, nokori):
    # print(data_left, nokori)
    while 1:
        if len(data_left) == 0:
            break
        if data_left[-1] <= 0:
            data_left.pop(-1)
            nokori += 1
        else:
            break

    # print(data_left, nokori)

    while nokori > 0:
        if len(data_left) == 0:
            break
        min_data = min(data_left)
        if min_data < 0:
            data_left.pop(data_left.index(min_data))
            nokori -= 1
        else:
            break
        # print('uuu', data_left)

    # print(data_left)

    while 1:
        if len(data_left) == 0:
            break
        saigo = data_left[-1]
        min_data = min(data_left)

        if saigo + min_data < 0:
            data_left.pop(-1)

            if len(data_left) == 0:
                nokori += 1
                break
            if min_data not in data_left:
                nokori += 1
            else:
                # print(data_left.index(min_data))
                data_left.pop(data_left.index(min_data))
        else:
            break

    return nokori, data_left

def main():

    num_houseki, num_sousa = map(int, input().split())
    data = list(map(int, input().split()))


    ans = 0


    # dp = defaultdict(int)

    for i in range(num_sousa + 1):

        nokori = 0
        left_ind = min(i, num_houseki)
        nokori += i - left_ind
        righ_ind = max(left_ind, num_houseki - num_sousa + i)
        nokori += num_sousa - i - num_houseki + righ_ind
        data_left = data[:left_ind]
        data_right = data[righ_ind:]

        # print('<><<><<><')
        # print(data_left)
        # print(data_right)


        nokori, data_left = get_data(data_left, nokori)
        nokori, data_right = get_data(data_right[::-1], nokori)
        data_right = data_right[::-1]

        # print('----')
        # print(data_left)
        # print(data_right)

        kari = sum(data_right) + sum(data_left)
        if kari > ans:
            ans = kari

    print(ans)







if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
v = list(map(int, input().split()))
ans = []
for i in range(k):
    p = []
    for j in range(k-i+1):
        left = v[:j]
        if j != k-i:
            right = v[-k+i+j:]
        else:
            right = []
        poyo = left + right
        mo = sum(poyo)
        for z in range(i):
            if poyo:
                mo -= poyo.pop(poyo.index(min(poyo)))
        p.append(mo)
    ans.append(max(p))
print(max(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+1, N+1)):
    for s in range(len(V)):
        part_Vi = Vi[s:s+k]
        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
        ans = max(ans, sum(part_V[plus_i:]))
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+1):
    for j in range(K-i):
        tmp = V[:i] + V[(N-j):]
        tmp.sort()
        for k, t in enumerate(tmp):
            if t>=0 or k+1 > K-i-j:
                ans = max(sum(tmp[k:]), ans)  
                break

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)
        for k2 in range(i):
            if minus[0] < 0:
                tmp += (-heapq.heappop(minus))
            else:
                break
#        print(ans,tmp,i,j,k)
        ans = max(ans,tmp)
    
print(ans)

Submission status: Wrong Answer

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

max_score = 0
max_l = min(k, n)
for l in range(max_l + 1):
    l_score = 0
    cand = []
    for i in range(l):
        cand.append(v_list[i])
    for i in range(l // 2 + 1):
        eraberu = l - i * 2
        cand2 = cand[:l-i]
        cand2.sort(reverse=True)
        s = sum(cand2[:eraberu])
        if s > l_score:
            l_score = s

    r = max_l - l
    r_score = 0
    cand = []
    for i in range(r):
        cand.append(v_list[len(v_list) - r + i])
    for i in range(r // 2 + 1):
        eraberu = r - i * 2
        cand2 = cand[i:]
        cand2.sort(reverse=True)
        s = sum(cand2[:eraberu])
        if s > r_score:
            r_score = s

    score = l_score + r_score
    if score > max_score:
        max_score = score
print(max_score)

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(max(a+1,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:
n, k = map(int, input().split())
a = [int(x) for x in input().split()]
mx = 0
for i in range(min(n, k)):
	for j in range(min(k - i + 1, n - i + 1)):
		summa = 0
		b = []
		for t in range(i):
			b.append(a[t])
		for t in range(n - j, n):
			b.append(a[t])
		z = k - i - j
		b.sort()
		for x in b:
			if x < 0 and z > 0:
				z -= 1
			else:
				summa += x
		mx = max(mx, summa)
print(mx)

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):
      for k in range(1, K - i - j  +1):
        available_v.append(sum(jv[k:]))

print(max(available_v))

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))
    if N==1:
        maximum = max(0, V_li[0])

    print(maximum)


main()

Submission status: Wrong Answer

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

best = 0

for i in range(k + 1):
  for j in range(min(i + 1, k - i + 1)):
    for m in range(i + 1):
      out = list(v[0:m]) + list(v[:-(i-m+1):-1])
      out.sort()
      best = max(best, sum(out[j::]))

print(best)

Submission status: Wrong Answer

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

max = 0
for i in range(k):
    for j in range(i+1):
        sp = i - j
        msp = -j
        if msp == 0:
            msp = len(v_)
        d = []
        d.extend(v_[:sp])
        d.extend(v_[msp:])
        d.sort()
        retmax = sum(d)
        for p in range(min(len(d), k-i)):
            if d[p] < 0:
                retmax -= d[p]
        if retmax > max:
            max = retmax
print(max)

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-l:])
            j = 0
            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+1:]))
            else:
                for j in range(K-i):
                    if n[j]>0:
                        break
                ans = max(ans,sum(n))
#            print(n)
#                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:
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(max(a//2+1,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:
N,K = list(map(int,input().split(" ")))
Vs = list(map(int,input().split(" ")))
rev = Vs[::-1]
ans = -(10e15)
for b in range(K+1):
    lr = K - b
    for l in range(lr + 1):
        rlim = lr - l
        for r in range(rlim+1):
            temoti = []
            temoti.extend(Vs[:l])
            temoti.extend(rev[:r])
            temoti.sort()
            tempans = sum(temoti)
            toridasi = 0
            for num in temoti:
                if toridasi == b: #上限回数取り出してたら終わり
                    break
                if num < 0:
                    tempans -= num
                    toridasi += 1
                else:
                    break

            if tempans > ans:
                ans = tempans
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)
        for k2 in range(len(minus)):
            if minus[0] < 0:
                tmp += (-heapq.heappop(minus))
            else:
                break
#        print(ans,tmp,i,j,k)
        ans = max(ans,tmp)
    
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)
    memo[key] = res
    return res

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

Submission status: Wrong Answer

Solution code:
N,K=map(int, input().split())
V=list(map(int, input().split()))
ans=0
from heapq import heapify,heappop
if N>K:
    for j in range(1,K+1):
        for k in range(j+1):
            x=V[:k]+V[N-j+k:]
            heapify(x)
            b=K-j
            if x[0]<0 and b>0:
                heappop(x)
                b-=1
            ans=max(ans,sum(x))
else:
    x=V
    heapify(V)
    b=K-N
    if x[0]<0 and b>0:
        heappop(x)
        b-=1
    ans=max(0,sum(x))
print(ans)

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 k in range(min(K, N)):
        for i in range(k+1):
            l = V[:i]
            r = V[N-(k-i):]
            lr = l + r
            lr.sort(reverse=True)

            for _ in range(K-k):
                if lr and lr[-1] < 0:
                    lr.pop()
                else:
                    break
            ans = max(ans, sum(lr))

    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()))
def dfs(k,v,t):
    if k==0:
        return sum(t)
    else:
        t=sorted(t)
        if len(v)==0:
            if t[0]<0:
                return(dfs(k-1,v,t[1:]))
            else:
                return sum(t)
        elif len(t)>0:
            if t[0]<0:
                return(max(dfs(k-1,v[1:],t+[v[0]]),dfs(k-1,v[:-1],t+[v[-1]]),dfs(k-1,v,t[1:])))
            else:
                return(max(dfs(k-1,v[1:],t+[v[0]]),dfs(k-1,v[:-1],t+[v[-1]])))
        else:
            return(max(dfs(k-1,v[1:],t+[v[0]]),dfs(k-1,v[:-1],t+[v[-1]])))
print(dfs(k,v,[]))

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)):
    at = k - backn

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

Submission status: Wrong Answer

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

max_score = 0
max_l = min(k, n)
for l in range(max_l + 1):
    l_score = 0
    cand = []
    for i in range(l):
        cand.append(v_list[i])
    for i in range(l // 2 + 1):
        eraberu = l - i * 2
        cand2 = cand[:l-i]
        cand2.sort(reverse=True)
        s = sum(cand2[:eraberu])
        if s > l_score:
            l_score = s

    r = max_l - l
    r_score = 0
    cand = []
    for i in range(r):
        cand.append(v_list[len(v_list) - r + i])
    for i in range(r // 2 + 1):
        eraberu = r - i * 2
        cand2 = cand[i:]
        cand2.sort(reverse=True)
        s = sum(cand2[len(cand2)-eraberu:])
        if s > r_score:
            r_score = s

    score = l_score + r_score
    if score > max_score:
        max_score = score
print(max_score)

Submission status: Wrong Answer

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

max = 0
for i in range(k):
    for j in range(i+1):
        sp = i - j
        msp = -j
        if msp == 0:
            msp = len(v_)
        print(v_[:sp], v_[msp:])
        d = []
        d.extend(v_[:sp])
        d.extend(v_[msp:])
        d.sort()
        retmax = sum(d)
        for p in range(min(len(d), k-i)):
            if d[p] < 0:
                retmax -= d[p]
        if retmax > max:
            max = retmax
print(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 >= 3 and n >= 2:
    ans = max([ans, v[1], v[-2]])
print(ans)

Submission status: Wrong Answer

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

# 何個捨てるか
ans = 0
for i in range(K):
    # 右から何個目まで取るか
    pick = q[:K-i]
    pick = sorted(pick)
    # print(pick)
    ans = max(sum(pick[i:]),ans)
    for j in range(K-i):
        pick = []
        pick = q[:j]+q[-(K-i-j):]
        # print(i,j,pick)
        pick = sorted(pick)
        ans = max(sum(pick[i:]),ans)
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()]

K = min(N, K)    

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:
# まず取り出しきっちゃってから捨てる
# 左右からいくつずつ取り出すか

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].copy()
    if R > 0:
      get += V[-R:].copy()
    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, input().split())
K_2 = (K+1)//2
V = list(map(int, input().split()))
mv = 0
for k in range(K_2):
    v = [V[:l]+V[-(K-k-l):] for l in range(K-k)]
    v.append(V[:K-k])
    v = [sorted(v[l])[k:] for l in range(K-k+1)]
    v = [sum(v[l]) for l in range(K-k+1)]
    if max(v) > mv:
        mv = max(v)
print(mv)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
a = [int(x) for x in input().split()]
mx = 0
for i in range(min(n, k)):
	for j in range(min(k - i, n - i)):
		summa = 0
		b = []
		for t in range(i):
			b.append(a[t])
		for t in range(n - j, n):
			b.append(a[t])
		z = k - i - j
		b.sort()
		for x in b:
			if x < 0 and z > 0:
				z -= 1
			else:
				summa += x
		mx = max(mx, summa)
print(mx)