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()))

vc_left = [0] * (K + 1)
minus_num = [0]
for i in range(N):
    if V[i] < 0:
        minus_num.append(-V[i])
        minus_num.sort(reverse=True)
    if i + 1 <= K:
        vc_left[i + 1] = max(vc_left[i + 1], sum(V[:i + 1]), vc_left[i])
    for j in range(1, len(minus_num)):
        if i+1+j <= K:
            vc_left[i+1+j] = max(vc_left[i + 1 + j], sum(V[:i + 1])+sum(minus_num[:j]), vc_left[i+j])
        if i == N-1 and j == len(minus_num) - 1 and i+1+j < K:
            for p in range(i+1+j+1, K+1):
                vc_left[p] = vc_left[p-1]

V.reverse()
vc_right = [0] * (K+1)
minus_num = [0]
for i in range(N):
    if V[i] < 0:
        minus_num.append(-V[i])
        minus_num.sort(reverse=True)
    if i + 1 <= K:
        vc_right[i + 1] = max(vc_right[i + 1], sum(V[:i + 1]), vc_right[i])
    for j in range(1, len(minus_num)):
        if i+1+j <= K:
            vc_right[i+1+j] = max(vc_right[i + 1 + j], sum(V[:i + 1])+sum(minus_num[:j]), vc_right[i+j])
        if i == N-1 and j == len(minus_num) - 1 and i+1+j < K:
            for p in range(i+1+j+1, K+1):
                vc_right[p] = vc_right[p-1]

ans_cand = [0] * (K+1)
for i in range(K+1):
    ans_cand[i] = vc_left[i] + vc_right[K-i]
print(max(ans_cand))

Submission status: Wrong Answer

Solution code:
n, k = [int(i) for i in input().split()]
V = [int(i) for i in input().split()]
plusList = [i >= 0 for i in V]
max_sum = 0
for ki in range(k+1):
    for mi in range(ki+1):
        for ii in range(ki-mi+1):
            inHand = V[:ki-mi-ii]+V[n-ii:]
            for jj in range(mi):
                inHand.sort()
                del inHand[:mi]
            if max_sum < sum(inHand):
                max_sum = sum(inHand)
print(max_sum)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")
from collections import deque
import heapq


def argmost(a, comp, ini):
    m, n = ini, -1
    for i, v in enumerate(a):
        if comp(m, v):
            m, n = v, i
    return m, n


def solve(N: int, K: int, V: "List[int]"):
    M = min(N, K)
    m = -INF
    for A in range(M+1):
        for B in range(M-A):
            jueries = V[:A] + V[N-B:]
            # print("before:", jueries)
            heapq.heapify(jueries)
            for i in range(K-A+B):
                if len(jueries) > 0:
                    sute = heapq.heappop(jueries)
                    if sute >= 0:
                        heapq.heappush(jueries, sute)
                        break
            s = sum(jueries)
            # print("after:", jueries, s)
            if m < s:
                m = s
    print(m)
    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:
import sys
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from copy import copy
import numpy as np
from numpy.fft import fft, ifft
from fractions import gcd


def input(): return sys.stdin.readline().strip()


def INT(): return int(input())


def MAP(): return map(int, input().split())


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


sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

n, k = MAP()

v = LIST()

m = int(n) + 1


lis = []
for h in range(k+1):
    for i in range(h+1):
        for j in range(h+1-i):
            #print(h,i,j)
            if j==0:
                #print(v[:i])
                lis.append(v[:i])
            else:
                #print(v[:i] + v[j:])
                lis.append(v[:i]+v[j:])

ans=0

for x in lis:
    a = x.copy()
    a.sort()
    for i in range(1, k - len(x) + 1):
        if a == []:
            break
        else:
            a.pop(0)
            #print(a)
            ans = max(ans, sum(a))

print(ans)

Submission status: Wrong Answer

Solution code:
def spaceinput():
    return list(map(int,input().split(" ")))

def gsum(l,r):
    return sum(V[l:(r)])
N,K=spaceinput()
V=spaceinput()

v_total=sum(V)
res=0
for nl in range(N):
    for nr in range(N-nl):
        k=nl+nr
        if k>=K:
            break
        l=nl
        r=N-nr-1
        if nl>0:
            temoto=V[:l]
        else:
            temoto=[]
        #print("temoto_l",temoto)
        if nr>0:
            temoto.extend(V[N-nr:])
        temoto=sorted(temoto)
        #tmp=v_total-gsum(l,r)
        tmp=sum(temoto)
        #print(temoto,tmp,v_total,gsum(l,r),r)
        for ss in range(K-len(temoto)):
            #print(ss)
            if ss>len(temoto)-1:
                break
            if temoto[ss]<0:
                tmp-=temoto[ss]
            else:
                break

        if tmp>res:
            res=tmp
            #print("koksin",res)
            #print(nl,nr)
            #print(l,r)
        

print(res)

Submission status: Wrong Answer

Solution code:
# 0~kまでx個左から取り、0~k-xまで右からy個取り、最後に0~k-x-yまで取ったうちで小さいやつを捨てる
n, k = map(int, input().split())
arr = list(map(int, input().split()))
ans = 0
for x in range(k + 1):
    for y in range(k - x + 1):
        for z in range(k - y + 1):
            if x + y < z or x + y + z > k:
                continue
            arr_tmpx = []
            arr_tmpy = []
            if x > 0:
                arr_tmpx = arr[:x]
            if y > 0:
                arr_tmpy = arr[-y:]
            arr_tmpx.extend(arr_tmpy)
            arr_tmpx = sorted(arr_tmpx)
            print(arr_tmpx)
            m = 0
            sorted_arr_tmpx = sorted(arr_tmpx)
            for zi in range(z):
                if sorted_arr_tmpx[zi] >= 0:
                    break
                m += sorted_arr_tmpx[zi]
            ans = max(ans, sum(arr_tmpx)-m)

print(ans)

Submission status: Wrong Answer

Solution code:
import copy

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

def calcMax(arr,K):
	maxValue = 0
	maxValue = max(maxValue,sum(arr))
	import heapq
	heap=[]
	for k in range(K):
		heapq.heappush(heap, arr[k])
		maxValue=max(maxValue,sum(heap))

		if 1 <= k:
			tmpHeap = copy.copy(heap)
			for _ in range(K-(k+1)):
				if 0 < len(tmpHeap):
					# print(k,K,tmpHeap)
					val=heapq.heappop(tmpHeap)
					maxValue=max(maxValue,sum(tmpHeap))

	# print(arr,K,maxValue)
	return maxValue



maxValue=0

for k in range(K+1):
	left=min(k,N)
	right=min(K-k,N)

	leftValue=0
	rightValue=0

	if 0 < left:
		leftValue=calcMax(V[:left],left)

	if 0 < right:
		tmp=V[N-right:]
		tmp=tmp[::-1]
		rightValue=calcMax(tmp,right)

	# print("---")
	maxValue = max(maxValue,leftValue+rightValue)



print(maxValue)

Submission status: Wrong Answer

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

combs = []
lim = min([N, K])
for a in range(0, lim + 1):
    for b in range(0, lim - a + 1):
          combs += ((a, b, c) for c in range(0, lim - a - b + 1))
# print(combs)
maxres = None
for c in combs:
    elems = D[:c[0]] + D[len(D) - c[1]:]
    elems.sort()
    res = sum(elems[c[2]:])
    if maxres == None:
        maxres = res
    elif maxres < res:
        maxres = res
print(maxres)

Submission status: Wrong Answer

Solution code:
#-*- coding:utf-8 -*-
from collections import deque

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

mn = min(N,K)   # 取り出せる個数
ans = 0
for a in range(mn+1):
    for b in range(mn+1-a):
        que = deque(V)
        have = []
        for i in range(a):  # 左からの取り出し
            have.append(que.popleft())
        for i in range(b):  # 右からの取り出し
            have.append(que.pop())
        have.sort()
        c = K - a - b
        for i in range(c):
            ans = max(ans, sum(have[c:]))

print(ans)

Submission status: Wrong Answer

Solution code:
import itertools as it
import collections as col
import heapq
import sys
sys.setrecursionlimit(10**9)
"""
N=int(input())
D=[]
for i in range(N):
  s,p=input().split()
  D.append((s, int(p), i+1))
D.sort(key=lambda d: (d[0], -d[1], d[2]))

for d in D:
  print(d[2])
"""
"""
N,M=map(int, input().split())
K=[]
S=[]
for i in range(M):
  k,*si=map(int, input().split())
  K.append(k)
  S.append(list(sorted(si)))
P=list(map(int, input().split()))

L=it.product([0,1], repeat=N)
cnt=0
#print(S)
for l in L:
  ok=True
  for i,si in enumerate(S):
    pi=P[i]
    sumS=len(list(filter(lambda it: l[it-1]==1, si)))
    #print(l, sumS)
    if sumS%2 != pi: ok=False
  if ok: cnt += 1
print(cnt)
"""
N,K=map(int,input().split())
V=col.deque(map(int, input().split()))
M=max(N,K)

ans=0

for l in range(M):
  for r in range(M):
    if l+r<=min(N,K):
      H=[]
      heapq.heapify(H)
      U=col.deque(V)
      for i in range(l):
        heapq.heappush(H, U.popleft())
      for i in range(r):
        heapq.heappush(H, U.pop())
      #print((l,r),U, H)
      i=0
      while H and i<K-l-r:
        rm=heapq.heappop(H)
        i += 1
        if rm>0:
          heapq.heappush(H, rm)
          break
      #print(sum(H), H)
      ans=max(ans, sum(H))
print(ans)

Submission status: Wrong Answer

Solution code:
N,  K = list(map(int, input().split()))
V = list(map(int, input().split()))
vleft = [0]
tmp = 0
for i in range(N):
    tmp += V[i]
    vleft.append(tmp)

vright= [0]
tmp = 0
for i in range(N):
    tmp += V[len(V) - i - 1]
    vright.append(tmp)

ans = 0

for i in range(K + 1):
    for j in range(i + 1):
        if i + j > N:
            break
        s = vleft[j] + vright[i - j]
        get = V[:j] + V[len(V) + j - i:]
        get.sort()
        minus = 0
        for k in range(min(len(get), K - i)):
            if get[k] < 0:
                minus += get[k]
        if ans < s - minus:
            ans = s - minus

print(ans)

Submission status: Wrong Answer

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

l = []
ans = 0
for a in range(K + 1):
  for b in range(K + 1 - a):
    l = V[0:a] + V[N - b:N]
    l.sort()
    for i in range(K - a - b + 1):
      ans = max(ans, sum(l[i:]))
print(max(ans, 0))

Submission status: Wrong Answer

Solution code:
import itertools as it
import collections as col
import heapq
import sys
sys.setrecursionlimit(10**9)
"""
N=int(input())
D=[]
for i in range(N):
  s,p=input().split()
  D.append((s, int(p), i+1))
D.sort(key=lambda d: (d[0], -d[1], d[2]))

for d in D:
  print(d[2])
"""
"""
N,M=map(int, input().split())
K=[]
S=[]
for i in range(M):
  k,*si=map(int, input().split())
  K.append(k)
  S.append(list(sorted(si)))
P=list(map(int, input().split()))

L=it.product([0,1], repeat=N)
cnt=0
#print(S)
for l in L:
  ok=True
  for i,si in enumerate(S):
    pi=P[i]
    sumS=len(list(filter(lambda it: l[it-1]==1, si)))
    #print(l, sumS)
    if sumS%2 != pi: ok=False
  if ok: cnt += 1
print(cnt)
"""
N,K=map(int,input().split())
V=col.deque(map(int, input().split()))
M=max(N,K)

ans=0

for l in range(M):
  for r in range(M):
    if l+r<=min(N,K):
      H=[]
      heapq.heapify(H)
      U=col.deque(V)
      for i in range(l):
        heapq.heappush(H, U.popleft())
      for i in range(r):
        heapq.heappush(H, U.pop())
      #print((l,r),U, H)
      i=0
      while H and i<K-l-r:
        rm=heapq.heappop(H)
        i += 1
        if rm>0:
          heapq.heappush(H, rm)
          break
      print(sum(H), H)
      ans=max(ans, sum(H))
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(" ")]

combs = []
lim = min([N, K])
for a in range(0, lim + 1):
    for b in range(0, lim - a + 1):
          combs += ((a, b, c) for c in range(0, lim - a - b + 1))
print(combs)
maxres = None
for c in combs:
    elems = D[:c[0]] + D[len(D) - c[1]:]
    elems.sort()
    res = sum(elems[c[2]:])
    if maxres == None:
        maxres = res
    elif maxres < res:
        maxres = res
print(maxres)

Submission status: Wrong Answer

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

l = []
ans = 0
for a in range(K + 1):
  for b in range(K + 1 - a):
    l = V[0:a] + V[N - b:N]
    l.sort()
    for i in range(K - a - b + 1):
      ans = max(ans, sum(l[i:]))
    ans = max(ans, sum(l))
print(max(ans, 0))

Submission status: Wrong Answer

Solution code:
[N,K]=list(map(int,input().split()))
V=list(map(int,input().split()))
have=[]
for n,k in enumerate(reversed(range(0,K+1))):
  tmp=[V[:ki]+V[-(k-ki):] for ki in range(k)
      ]+[V[:k],]
  #print(n,tmp)
  if n!=0:
    for num_remove in range(n):
      tmp2=[sorted(item)[n:] for item in tmp]

      tmp.extend(tmp2)
      #print("tmp",tmp)
      
  have.extend(tmp)
  #print(n,have[-1])
  
print(max(list(map(sum,have
                  )
              )
         )
     )

Submission status: Wrong Answer

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

combs = []
lim = min([N, K])
for a in range(0, lim + 1):
    for b in range(0, lim - a):
          combs += ((a, b, c) for c in range(0, lim - a - b + 1))
maxres = None
for c in combs:
    elems = D[:c[0]] + D[len(D) - c[1]:]
    elems.sort()
    res = sum(elems[c[2]:])
    if maxres == None:
        maxres = res
    elif maxres < res:
        maxres = res
print(maxres)

Submission status: Wrong Answer

Solution code:
#-*- coding:utf-8 -*-
from collections import deque

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

mn = min(N,K)   # 取り出せる個数
ans = 0
for a in range(mn+1):
    for b in range(mn+1-a):
        que = deque(V)
        have = []
        for i in range(a):  # 左からの取り出し
            have.append(que.popleft())
        for i in range(b):  # 右からの取り出し
            have.append(que.pop())
        have.sort()
        c = K - a - b
        if c >= N:
            continue
        ans = max(ans, sum(have[c:]))

print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin

def main():
     def max_n_main(oku,kosu_s,kosu_e):
          if len(v)>oku:
               ans = max_n_sub(oku,kosu_s,kosu_e,v[:oku])
               ans = max(ans,max_n_sub(oku,kosu_s,kosu_e,v[len(v)-oku+1:]))
               for i in range(1,oku):
                    tmpv = v[:i]+v[len(v)-oku+i:]
                    ans = max(ans,max_n_sub(oku,kosu_s,kosu_e,tmpv))
               return ans
          elif len(v)==oku:
               return max(0,max_n_sub(oku,kosu_s,kosu_e,v))
          else:
               return 0
               
     def max_n_sub(oku,kosu_s,kosu_e,tmpv):#奥行きokuから個数kosu_sから個数kosu_eの間の個数をとる時価値が最大な値を返す
          tmpv.sort()
          ko = 0
          ans = 0
          for i in range(len(tmpv)):
               if ko < kosu_s:
                    ans += tmpv[len(tmpv)-i-1]
                    ko += 1
               else:
                    if ko == kosu_e:
                         break
                    elif tmpv[len(tmpv)-i-1]>0:
                         ans += tmpv[len(tmpv)-i-1]
                         ko += 1
                    else:
                         break
          return ans
          
     n,k= [int(x) for x in stdin.readline().split()]
     v = [int(x) for x in stdin.readline().split()]
     ans = 0
     for ki in range(1,k):
          ans = max(ans,max_n_main(ki,max(1,2*ki-k),ki))
     print(ans)
     return 0
     
if __name__ == '__main__':
     main()

Submission status: Wrong Answer

Solution code:
import copy
N,KK = map(int,input().split())
V = list(map(int,input().split()))
# N = 40
# K = 100
# V = [i for i in range(N)]

# V = [0 for i in range(N)] + V + [0 for i in range(N)] 

sumval = 0
for K in range(KK+1):
    for sute in range(K):
        for i in range(K-sute):
            # print(V[:K-sute-i], V[N-i:])
            sV = sorted(V[:min(K-sute-i,N) ]+ V[N-i:])
            # print(sV[sute:])
            sumval = max(sum(sV[sute:]),sumval)

print(sumval)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
ans=[]
for lhs in range(k+1):
    for rhs in range(k-lhs+1):
        cnt=v[:lhs]+v[n-rhs:]
        # print(v[:lhs],v[n-rhs:])
        for i in range(k+1-lhs-rhs):
            cnt.sort()
            ans.append(sum(cnt[i:]))
# print(ans)
print(max(ans))

Submission status: Wrong Answer

Solution code:
def spaceinput():
    return list(map(int,input().split(" ")))

def gsum(l,r):
    return sum(V[l:(r)])
N,K=spaceinput()
V=spaceinput()

v_total=sum(V)
res=0
for nl in range(N):
    for nr in range(N-nl):
        k=nl+nr
        if k>=K:
            break
        l=nl
        r=N-nr-1
        if nl>0:
            temoto=V[:l]
        else:
            temoto=[]
        #print("temoto_l",temoto)
        if nr>0:
            temoto.extend(V[N-nr:])
        temoto=sorted(temoto)
        #tmp=v_total-gsum(l,r)
        tmp=sum(temoto)
        #print(temoto,tmp,v_total,gsum(l,r),r)
        for ss in range(K-len(temoto)):
            #print(ss)
            if ss>=len(temoto)-1:
                break
            if temoto[ss]<0:
                tmp-=temoto[ss]
            else:
                break

        if tmp>res:
            res=tmp
            #print("koksin",res)
            #print(nl,nr)
            #print(l,r)
        

print(res)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(100000)

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


ans = 0
for i in range(K+1):
  hand = V[:i]
  for j in range(K-i+1):
    if j != 0:
      x = hand + V[max(K-j, i):]
    else:
      x = hand
    rest = K - i - j
    summ = sum(v for i, v in enumerate(sorted(x)) if i >= rest or v > 0)
    ans = max(ans, summ)
    # print(f"K={K}, i={i}, j={j}, rest={rest}, sum={summ}, x={x}")
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun May 26 22:52:59 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):
            if V[k-j] > 0:
                tmp += V[k-j]
            else:
                heapq.heappush(minus,V[k-j])
#            print(tmp)
#            heapq.heappush(minus,V[k-j])
#        for k2 in range(i):
#            if minus[0] < 0:
#                tmp += (-heapq.heappop(minus))
#            else:
#                break
        for k2 in range(min(i,len(minus))):
            heapq.heappop(minus)
        tmp += sum(minus)
#        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(map(int, input().split()))

vc_left = [0] * (K + 1)
minus_num = [0]
for i in range(N):
    if V[i] < 0:
        minus_num.append(-V[i])
        minus_num.sort(reverse=True)
    if i + 1 <= K:
        vc_left[i + 1] = max(vc_left[i + 1], sum(V[:i + 1]), vc_left[i])
    for j in range(1, len(minus_num)):
        if i+1+j <= K:
            vc_left[i+1+j] = max(vc_left[i + 1 + j], sum(V[:i + 1])+sum(minus_num[:j]), vc_left[i+j])
V.reverse()
vc_right = [0] * (K+1)
minus_num = [0]
for i in range(N):
    if V[i] < 0:
        minus_num.append(-V[i])
        minus_num.sort(reverse=True)
    if i + 1 <= K:
        vc_right[i + 1] = max(vc_right[i + 1], sum(V[:i + 1]), vc_right[i])
    for j in range(1, len(minus_num)):
        if i+1+j <= K:
            vc_right[i+1+j] = max(vc_right[i + 1 + j], sum(V[:i + 1])+sum(minus_num[:j]), vc_right[i+j])

ans_cand = [0] * (K+1)
for i in range(K+1):
    ans_cand[i] = vc_left[i] + vc_right[K-i]
print(max(ans_cand))

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 left in range(K+1):
    for right in range(K+1-left):
        back = K - left - right
        tmp_list = V[:left] + V[N-right:]
        tmp_list.sort()
        index = 0
        t = min(len(tmp_list), back)
        for i in range(t):
            if tmp_list[i] >= 0:
                break
            index += 1
        if index == back-1:
            index += 1
        tmp = sum(tmp_list[index:])
        if tmp > ans:
            ans = tmp

print(ans)

Submission status: Wrong Answer

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

ans = 0
for i in range(k+1):
    tmp = []
    for j in range(i+1):
        choice = v[:j] + v[-(i-j):]
        if i != j:
            if choice not in tmp:
                tmp.append(choice)
            #print(choice)
        else:
            #print(v[:j])
            tmp.append(v[:j])
    for cho in tmp:
        cho.sort()
        cho.reverse()
        #print(cho)
        for back in range(k-len(cho)+1):
            tmpo = sum(cho[:len(cho) - back])
            #print(tmpo)
            ans = max(ans, tmpo)

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy


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


memo = {}


def best_op(v_list, hand, k):
    # print('call ', v_list, hand, k)
    if (tuple(v_list.tolist()), tuple(hand.tolist()), k) in memo:
        # print('hit')
        return memo[(tuple(v_list.tolist()), tuple(hand.tolist()), k)]
    if k == 0:
        # print('return')
        return sum(hand)
    if k > 0:
        # print('a')
        # print(v_list, hand)
        v_list_a, hand_a, succ = op_a(v_list, hand)
        if succ:
            sum_a = best_op(v_list_a, hand_a, k - 1)
            if not (tuple(v_list_a.tolist()), tuple(hand_a.tolist()), k - 1) in memo:
                memo[(tuple(v_list_a.tolist()), tuple(hand_a.tolist()), k - 1)] = sum_a
        else:
            sum_a = -10 ** 7 * k

        # print('b')
        # print(v_list, hand)
        v_list_b, hand_b, succ = op_b(v_list, hand)
        if succ:
            sum_b = best_op(v_list_b, hand_b, k - 1)
            if not (tuple(v_list_b.tolist()), tuple(hand_b.tolist()), k - 1) in memo:
                memo[(tuple(v_list_b.tolist()), tuple(hand_b.tolist()), k - 1)] = sum_b
        else:
            sum_b = -10 ** 7 * k

        # print('c')
        v_list_c, hand_c, succ = op_c(v_list, hand)
        if succ and (len(hand) == 0 or hand[0] > 0):
            sum_c = best_op(v_list_c, hand_c, k - 1)
            if not (tuple(v_list_c.tolist()), tuple(hand_c.tolist()), k - 1) in memo:
                memo[(tuple(v_list_c.tolist()), tuple(hand_c.tolist()), k - 1)] = sum_c
        else:
            sum_c = -10 ** 7 * k

        # print('d')
        v_list_d, hand_d, succ = op_d(v_list, hand)
        if succ and (len(hand) == 0 or hand[0] > 0):
            sum_d = best_op(v_list_d, hand_d, k - 1)
            if not (tuple(v_list_d.tolist()), tuple(hand_d.tolist()), k - 1) in memo:
                memo[(tuple(v_list_d.tolist()), tuple(hand_d.tolist()), k - 1)] = sum_d
        else:
            sum_d = -10 ** 7 * k

        v_list_e, hand_e, succ = v_list, hand, True
        sum_e = best_op(v_list_e, hand_e, k - 1)

        # print(sum_a, sum_b, sum_c, sum_d)
        return max(sum_a, sum_b, sum_c, sum_d, sum_e)


def op_a(v_list, hand):
    if len(v_list) == 0:
        return v_list, hand, False
    value = v_list[0]
    v_list = numpy.delete(v_list, 0)
    hand = numpy.append(hand, value)
    hand.sort()
    return v_list, hand, True


def op_b(v_list, hand):
    if len(v_list) == 0:
        return v_list, hand, False
    value = v_list[len(v_list) - 1]
    v_list = numpy.delete(v_list, len(v_list) - 1)
    hand = numpy.append(hand, value)
    hand.sort()
    return v_list, hand, True


def op_c(v_list, hand):
    if len(hand) == 0:
        return v_list, hand, False
    min_val = hand[0]
    hand = numpy.delete(hand, 0)
    v_list = numpy.insert(v_list, 0, min_val)
    return v_list, hand, True


def op_d(v_list, hand):
    if len(hand) == 0:
        return v_list, hand, False
    min_val = hand[0]
    hand = numpy.delete(hand, 0)
    v_list = numpy.append(v_list, min_val)
    return v_list, hand, True


if __name__ == '__main__':
    [n, k] = li()
    v_list = li()
    v_list = numpy.array(v_list, dtype=numpy.int64)
    hand = numpy.array([], dtype=numpy.int64)

    # print(n, k)
    # print(v_list)
    print(max(best_op(v_list, hand, k), 0))

Submission status: Wrong Answer

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

l = []
ans = 0
for a in range(K + 1):
  for b in range(K + 1 - a):
    l = V[:a] + V[N - b:]
    l.sort()
    for _ in range(K - a - b):
      if len(l) > 0 and l[0] < 0:
        l.pop(0)
      else:
        break
    ans = max(ans, sum(l))
print(max(ans, 0))

Submission status: Wrong Answer

Solution code:
import copy
import heapq

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

maximum = 0
for k in range(K):
    for offset in range(k):
        acc = 0
        heap = []
        for j in range(k):
            vs = V[j-offset:j-offset+1]
            if vs:
                v = vs[0]
                if v < 0:
                    heapq.heappush(heap, v)
                acc += v
        for m in range(K-k):
            if len(heap) > 0:
                acc -= heapq.heappop(heap)
        maximum = max(maximum, acc)

print(maximum)

Submission status: Wrong Answer

Solution code:
import sys
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from copy import copy
import numpy as np
from numpy.fft import fft, ifft
from fractions import gcd


def input(): return sys.stdin.readline().strip()


def INT(): return int(input())


def MAP(): return map(int, input().split())


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


sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

n, k = MAP()

v = LIST()

m = int(n) + 1


lis = []
for h in range(k+2):
    for i in range(h):
        j = i - h+1
        #print(i,j)
        if j==0:
            #print(v[:i])
            lis.append(v[:i])
        else:
            #print(v[:i] + v[j:])
            lis.append(v[:i]+v[j:])

ans=0

for x in lis:
    a = x.copy()
    a.sort()
    for i in range(1, k - len(x) + 1):
        if a == []:
            break
        else:
            a.pop(0)
            #print(a)
            ans = max(ans, sum(a))

print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
import math
import fractions
from collections import deque
import itertools

INF = 10 ** 10

N, K = [int(x) for x in stdin.readline().rstrip().split()]
V = []
for vi in stdin.readline().rstrip().split():
    V.append(int(vi))

ans = 0

for i in range(K//2+1, K+1):
    toru = i
    sute = K-i

    #print(toru)
    #print(sute)
    
    for j in range(toru+1):
        leftn = j
        rightn = (toru - j)*-1

        #print(leftn, rightn)

        if rightn == 0:
            data = V[:leftn]
        elif leftn == 0:
            data = V[rightn:]
        else:
            data = V[:leftn] + V[rightn:]
        #print(data)

        for _ in range(sute):
            data.sort()
            if data[0] < 0:
                del data[0]

        #print(data)

        ans = max(ans, sum(data))

print(ans)

Submission status: Wrong Answer

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

max_log = []

for total_take in range(K + 1):
    for left_take in range(total_take + 1):
        right_take = total_take - left_take
        taken_set = V[:left_take] + (V[-right_take:] if right_take != 0 else [])
        taken_set.sort(reverse=True)
        l = len(taken_set)

        if taken_set == []:
            continue
        else:
            for _ in range(1, min(K - total_take, l) + 1):
                if taken_set[-1] < 0:
                    taken_set.pop()
                    if taken_set == []:break
                else:
                    break

        max_log.append(sum(taken_set))

print(max(max_log))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for pull in range(k + 1):
    for back in range(k):
        if pull + back != k:
            continue
        if pull >= n:
            hand = V
        else:
            for l in range(pull+1):
                r = pull - l
                if r > 0:
                    hand = V[:l] + V[-r:]
                else:
                    hand = V[:l]
        hand = sorted(hand, reverse=True)
        for _ in range(back):
            if len(hand) == 0:
                break
            if hand[-1] < 0:
                hand.pop()
            else:
                break
        ans = max(ans, sum(hand))
print(ans)