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: Runtime Error

Solution code:
def A(lst,hand):
    if len(lst) == 0:
        return
    else:
        return lst.pop(0)

def B(lst,hand):
    if len(lst) == 0:
        return
    else:
        return lst.pop(len(lst)-1)

def C(lst,hand):
    if len(hand) == 0:
        return
    else:
        lst.insert(0 , hand.pop( hand.index(min(hand)) ))

def D(lst,hand):
    if len(hand) == 0:
        return
    else:
        lst.append(hand.pop( hand.index(min(hand))) )

import random

if __name__ == "__main__":
    N,K = map(int, input().split())
    V = input().split()
    V = [int(i) for i in V]
    hand = []

    for l in range(1000):
        V_copy = [i for i in V]
        hand_copy = []
        for i in range(K):
            rand = random.randint(1,4)
            if rand == 1:
                hand_copy.append(A(V_copy,hand_copy))
            elif rand == 2:
                hand_copy.append(B(V_copy,hand_copy))
            elif rand == 3:
                C(V_copy,hand_copy)
            else:
                D(V_copy,hand_copy)
        hand.append(hand_copy)

    x = []
    for i in range(1000):
        x.append(sum(hand[i]))
    print(max(x))

Submission status: Runtime Error

Solution code:
from collections import deque
n,k=map(int,input().split())
v=[int(_) for _ in input().split()]
num=min(n,k)
fans=0
for lll in range(num):
  for rrr in range(num-lll):
    rest=k-lll-rrr
    if rrr!=0:
      pick=v[:lll]+v[-rrr:]
    else:
      pick=v[:lll]
  ans=sum(pick)
  pick=sorted(pick)
  for iii in range(rest):
    if pick[iii]<0:
      ans-=pick[iii]
  fans=max(ans,fans)
print(fans)

Submission status: Runtime Error

Solution code:
import sys, heapq
from collections import deque
input = sys.stdin.readline
'''
allinputs = iter(input().splitlines())
input = lambda : next(allinputs)
#'''

N, K = map(int, input().split())
V_init = deque(map(int, input().split()))
max_score = 0
hands = [0] * K
heapq.heapify(hands)

for i_rget in range(K + 1):
	for i_lget in range(max(K - i_rget, 0) + 1):
		for i_del in range(max(K - i_rget - i_lget, 0) + 1):
			score = 0
			hands = [0] * K
			V = deque.copy(V_init)
			for i in range(i_rget + 1):
				if i > 0 and V:
					tmp = V.pop()					
					heapq.heappush(hands, tmp)
					score += tmp
				
			for i in range(i_lget + 1):
				if i > 0 and V:
					tmp = V.popleft()
					heapq.heappush(hands, tmp)
					score += tmp
			
			for i in range(i_del + 1):
				if i > 0:
					tmp = heapq.heappop(hands)
					score -= tmp
			
			if score > max_score:
				max_score = score

print(max_score)

Submission status: Runtime Error

Solution code:
import sys, heapq
from collections import deque
input = sys.stdin.readline
'''
allinputs = iter(input().splitlines())
input = lambda : next(allinputs)
#'''

N, K = map(int, input().split())
V_init = deque(map(int, input().split()))
max_score = 0
hands = [0] * K
heapq.heapify(hands)

for i_rget in range(K + 1):
	for i_lget in range(max(K - i_rget, 0) + 1):
		for i_del in range(max(K - i_rget - i_lget, 0) + 1):
			score = 0
			hands = [0] * K
			V = deque.copy(V_init)
			for i in range(i_rget + 1):
				if i > 0 and V:
					tmp = V.pop()					
					heapq.heappush(hands, tmp)
					score += tmp
				
			for i in range(i_lget + 1):
				if i > 0 and V:
					tmp = V.popleft()
					heapq.heappush(hands, tmp)
					score += tmp
			
			for i in range(i_del + 1):
				if i > 0:
					tmp = heapq.heappop(hands)
					score -= tmp
			
			if score > max_score:
				max_score = score

print(max_score)

Submission status: Runtime Error

Solution code:
import copy
import sys

n, k = map(int, sys.stdin.readline().split())
v = list(map(int, sys.stdin.readline().split()))


def check_left(i):
    left_max = 0
    t = []
    for j in range(i):
        t.append(v[j])
        u = copy.copy(t)

        for _ in range(i - j):
            if left_max < sum(u):
                left_max = sum(u)
            if len(u) != 0:
                u.remove(min(u))
    return left_max


def check_right(i):
    right_max = 0
    t = []
    for j in range(i):
        t.append(v[n - j - 1])
        u = copy.copy(t)

        for _ in range(i - j):
            if right_max < sum(u):
                right_max = sum(u)
            if len(u) != 0:
                u.remove(min(u))
    return right_max


ans = 0


for i in range(k + 1):
    t = check_left(i) + check_right(k - i)
    if ans < t:
        ans = t

print(ans)

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
V_list = list(map(int,input().split()))
min_ = min(N,K)
total = []
#get
for a in range(min_):
  for b in range(min_-a):
    score_get = V_list[:a]+V_list[N-b:]
    score_get.sort()
    if len(score_get) == 0:
      score_get.append(0)
    for i in range(min(K-(a+b)+1,len(score_get))):
      if score_get[i]<0:
        new_score = score_get[:i]+score_get[i+1:]
      else:
        break
      total_score = sum(new_score)
      total.append(total_score)
print(max(total))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
d=list(map(int,input().split()))
d=d*2
ans=0
for i in range(1,k+1):
  
  for j in range(i+1):
    have=[d[n+c-j] for c in range(i)] #ここにi個の宝石を入れる
    have.sort()
    if i!=k:
      for h in range(k-i):
        if have==[] or have[0]>=0:
          break
        del have[0]
      #いらない宝石を可能な限り詰めた状態
    if sum(have)>ans:
      ans=sum(have)
print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
d=list(map(int,input().split()))
d=d*2
ans=0
for i in range(1,k+1):
  
  for j in range(i+1):
    have=[d[n+c-j] for c in range(i)] #ここにi個の宝石を入れる
    have.sort()
    print(have)
    if i!=k:
      for h in range(k-i):
        if have==[] or have[0]>=0:
          break
        del have[0]
      #いらない宝石を可能な限り詰めた状態
    if sum(have)>ans:
      ans=sum(have)
print(ans)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
d=list(map(int,input().split()))
d=d*2
ans=0
for i in range(k):
  
  for j in range(i+1):
    have=[d[n+c-j] for c in range(i)] #ここにi個の宝石を入れる
    have.sort()
    for h in range(k-i):
      if have[0]>=0:
        break
      del have[0]
    #いらない宝石を可能な限り詰めた状態
    if sum(have)>ans:
      ans=sum(have)
print(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
v = list(map(int, input().split()))
ans = 0 
# left
for i in range(min(n, k) + 1):
    # right
    for j in range(min(n, k) - i + 1):
        par_seq = sorted(v[:i] + v[-j:] if j != 0 else v[:i])
        par_seq_sum = sum(par_seq)
        if par_seq_sum > ans:
            ans = par_seq_sum
        m = k - (i + j)
        tmp = max([sum(par_seq[i:]) for i in range(min(m, len(par_seq)))])
        if tmp > ans:
          ans = tmp
print(ans)

Submission status: Runtime Error

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

def solve(L, R, D):
  # print((L, R, D))
  LL = v[:L] if L > 0 else []
  RR = v[-R:] if R > 0 else []
  targetList = LL + RR
  # print(targetList)
  targetList.sort()
  ret = 0
  newList = targetList.copy()
  for i in range(min(len(targetList), D)):
    if targetList[i] < 0:
      del newList[0]
  ret = sum(newList)
  # print((ret, newList))
  return ret

result = 0
for i in range(min(k+1, n+1)):
  for j in range(min(k+1, n+1)-i):
    t = solve(i, j, k-i-j)
    if t > result:
      result = t

print(result)

Submission status: Runtime Error

Solution code:
# Technique often used
# enumerate: for i, a in enumerate(a_list):
# Functional Programming: filter, map, reduce

# naming conventions
# if [s_1, s_2, s_3, ..., s_k] then I name this list sk
# if [[s_11, s_12, ..., s_1k], ..,[s_j1, s_j2, ..., s_jk] then I name this list sjk
# if something strange in list then I add _ to list's name (ex:sjk_)

# visual studio code shortcut https://qiita.com/TakahiRoyte/items/cdab6fca64da386a690b
# delete line: Ctrl+Shift+k
# choose same words: Ctrl+Shift+l

from itertools import combinations # https://docs.python.org/ja/3/library/itertools.html#itertools.combinations
from itertools import permutations # https://docs.python.org/ja/3/library/itertools.html#itertools.permutations
from collections import deque # https://docs.python.org/ja/3/library/collections.html#collections.deque
import heapq # priority_queue
import copy
def gcd(a,b):
    if b==0:return a
    return gcd(b,a%b)
def gcds(a):
    if len(a)==1:
        return a[0]
    else:
        element = gcd(a[0], a[1])
        if len(a)==2:return(element)
        else:
            for i in range(2,n):
                element=gcd(element,a[i])
            return(element)

is_test = False
def debug_print(a,comments="",is_test=is_test):
    # debug_print([]) => []
    # debug_print("") => 
    # debug_print(a, "a is") => "a is:" print(a)
    if not is_test:
        pass
    elif not comments and a is None:
        print("")
    elif not comments:
        print(a)
    else:
        print(comments,":",a)

# setting the inputs
if is_test:
    n,k = [6, 4]
    vn = [-6, -100, 50, -2, -5, -3]
    # vn = [-10, 8, 2, 1, 2, 6]
else:        
    n,k = map(int,input().split())
    vn = [int(i) for i in input().split()]

hp = []
ans = 0
for i in range(k+1):
    if i == 0:
        pass
    else:
        heapq.heappush(hp,vn[i-1])
    hpj = copy.deepcopy(hp)
    for j in range(k-i+1):
        if j == 0:
            pass
        else:
            heapq.heappush(hpj,vn[n-j])
        hpjj = copy.deepcopy(hpj)
        debug_print(hpjj)
        counter = 0
        if i==0 and j==0:
            pass
        else:            
            while hpjj[0] < 0 and counter < k-i-j:
                counter += 1
                heapq.heappop(hpjj)
                if len(hpjj)==0:
                    break
        ans = max(ans, sum(hpjj))

print(ans)

Submission status: Runtime Error

Solution code:
# Technique often used
# enumerate: for i, a in enumerate(a_list):
# Functional Programming: filter, map, reduce

# naming conventions
# if [s_1, s_2, s_3, ..., s_k] then I name this list sk
# if [[s_11, s_12, ..., s_1k], ..,[s_j1, s_j2, ..., s_jk] then I name this list sjk
# if something strange in list then I add _ to list's name (ex:sjk_)

# visual studio code shortcut https://qiita.com/TakahiRoyte/items/cdab6fca64da386a690b
# delete line: Ctrl+Shift+k
# choose same words: Ctrl+Shift+l

from itertools import combinations # https://docs.python.org/ja/3/library/itertools.html#itertools.combinations
from itertools import permutations # https://docs.python.org/ja/3/library/itertools.html#itertools.permutations
from collections import deque # https://docs.python.org/ja/3/library/collections.html#collections.deque
import heapq # priority_queue
import copy
def gcd(a,b):
    if b==0:return a
    return gcd(b,a%b)
def gcds(a):
    if len(a)==1:
        return a[0]
    else:
        element = gcd(a[0], a[1])
        if len(a)==2:return(element)
        else:
            for i in range(2,n):
                element=gcd(element,a[i])
            return(element)

is_test = False
def debug_print(a,comments="",is_test=is_test):
    # debug_print([]) => []
    # debug_print("") => 
    # debug_print(a, "a is") => "a is:" print(a)
    if not is_test:
        pass
    elif not comments and a is None:
        print("")
    elif not comments:
        print(a)
    else:
        print(comments,":",a)

# setting the inputs
if is_test:
    n,k = [6, 4]
    vn = [-6, -100, 50, -2, -5, -3]
    # vn = [-10, 8, 2, 1, 2, 6]
else:        
    n,k = map(int,input().split())
    vn = [int(i) for i in input().split()]

hp = []
ans = 0
for i in range(k+1):
    if i == 0:
        pass
    else:
        heapq.heappush(hp,vn[i-1])
    hpj = copy.deepcopy(hp)
    for j in range(k-i+1):
        if j == 0:
            pass
        else:
            heapq.heappush(hpj,vn[n-j])
        hpjj = copy.deepcopy(hpj)
        debug_print("hpjj",hpjj,is_test)
        counter = 0
        if i==0 and j==0:
            pass
        else:            
            while hpjj[0] < 0 and counter < k-i-j:
                counter += 1
                heapq.heappop(hpjj)
                if len(hpjj)==0:
                    break
        ans = max(ans, sum(hpjj))

print(ans)

Submission status: Runtime Error

Solution code:
from bisect import*
import sys;input=sys.stdin.readline

def doevent(lis):
    global stop
    a,b=lis
    if b>=0:
        if stop=={-1}:
            stop=set()
        stop.add(b)
    else:
        if -b in stop:
            stop.remove(-b)
        if stop==set():
            stop={-1}
    return min(stop)

stop=set([-1])
def main():
    n,q=map(int,input().split())
    event=[]
    
    for i in range(n):
        s,t,x=map(int,input().split())
        event.append((s-x,x))
        event.append((t-x,-x))
    event.sort(key=lambda x:x[0])
    minlist=[doevent(i)for i in event] #時間をindexとしたminlist

    for i in range(q):
        print(minlist[bisect_right(event,(int(input()),10**9))-1])
if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

if K <= 2:
    print(max(V[0], V[1], 0))
    quit()


ans = 0
for a in range(min(N, K)+1):
    for b in range(min(N-a, K-a)+1):
        V_ = sorted(V[:a] + V[-b:]) if b >= 1 else sorted(V[:a])
        tmp = K - (a+b)
        curMinus = 0
        for v in V_:
            if v < 0 and tmp > 0:
                tmp -= 1
                curMinus += -v
        ans = max(ans, sum(V_)+curMinus)

print(ans)

Submission status: Runtime Error

Solution code:
[_, input_k] = map(int, input().split())

input_v = list(map(int, input().split()))

max_value = 0

for a in range(min(input_v, input_k + 1)):
    for b in range(min(input_v, input_k - a + 1)):
        if (b != 0):
            hold_jewelries = input_v[:a] + input_v[-b:]
        else:
            hold_jewelries = input_v[:a]
        hold_jewelries = sorted(hold_jewelries)

        remove_length = input_k - a - b 
        hold_minus = sum(1 for value in hold_jewelries if value < 0)

        hold_value = sum(hold_jewelries[min(hold_minus, remove_length):])

        if (hold_value > max_value):
            max_value = hold_value

print(max_value)

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
D_mem = list(map(int, input().split()))
ans = 0

for i in range(2**min(N, K)):
  for j in range(min(N, K)):
      D = D_mem
      H = []
      for j1 in range(j):
        if (i>>j1) == 0:
          H.append(D[0])
          D = D[1:]
        else:
          H.append(D[-1])
          D = D[:-1]
      H.sort()
      for _ in range(min((K-j), len(H))):
        if H[0] < 0:
          H = H[1:]
        else:
          break
        val = sum(H)
  if ans < val:
      ans = val

print(ans)

Submission status: Runtime Error

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

m = k // 2 + (k % 2)

a = [0] * (n+1)
d = [0] * (n+1)

a[0] = 0
d[n] = 0
for i in range(n):
    a[i+1] = a[i] + v[i]
    d[n-1-i] = d[n-i] + v[n-1-i]

w = []
for i in range(n):
    w.append([v[i], i])

w.sort()

ans = 0

sv = sum(v)

for i in range(m):
    p = k - i
    if p >= n:
        temp = sv
        for _ in range(i):
            if w[i][0] >= 0:
                break
            temp -= w[i][0]
        ans = max(temp, ans)
    else:
        for j in range(p+1):
            #print(j, n-p-j, a[j], d[n-p-j])
            temp = a[j] + d[n-p+j]
            c = 0
            for _ in range(i):
                if w[c][0] >= 0:
                    break
                if w[c][1] < j or w[c][1] > n-p+j:
                    temp -= w[c][0]
                c += 1
                if c >= n:
                    break
            ans = max(temp, ans)

print(ans)

Submission status: Runtime Error

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

m = k // 2 + (k % 2)

a = [0] * (n+1)
d = [0] * (n+1)

a[0] = 0
d[n] = 0
for i in range(n):
    a[i+1] = a[i] + v[i]
    d[n-1-i] = d[n-i] + v[n-1-i]

w = []
for i in range(n):
    w.append([v[i], i])

w.sort()

ans = 0

#print(a)
#print(d)

for i in range(m):
    p = k - i
    for j in range(p+1):
        #print(j, n-p-j, a[j], d[n-p-j])
        temp = a[j] + d[n-p+j]
        c = 0
        for _ in range(i):
            if w[c][0] >= 0:
                break
            if w[c][1] < j or w[c][1] > n-p+j:
                temp -= w[c][0]
            c += 1
            if c >= n:
                break
        ans = max(temp, ans)

print(ans)

Submission status: Runtime Error

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

m = k // 2 + (k % 2)

a = [0] * (n+1)
d = [0] * (n+1)

a[0] = 0
d[n] = 0
for i in range(n):
    a[i+1] = a[i] + v[i]
    d[n-1-i] = d[n-i] + v[n-1-i]

w = []
for i in range(n):
    w.append([v[i], i])

w.sort()

ans = 0

#print(a)
#print(d)

for i in range(m):
    p = k - i
    for j in range(p+1):
        #print(j, n-p-j, a[j], d[n-p-j])
        temp = a[j] + d[n-p+j]
        c = 0
        for _ in range(i):
            if w[c][0] >= 0:
                break
            if w[c][1] < j or w[c][1] > n-p+j:
                temp -= w[c][0]
            c += 1


        ans = max(temp, ans)

print(ans)

Submission status: Runtime Error

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

m = k // 2 + (k % 2)

a = [0] * (n+1)
d = [0] * (n+1)

a[0] = 0
d[n] = 0
for i in range(n):
    a[i+1] = a[i] + v[i]
    d[n-1-i] = d[n-i] + v[n-1-i]

w = []
for i in range(n):
    w.append([v[i], i])

w.sort()

ans = 0

for i in range(m):
    p = k - i
    for j in range(p+1):
        #print(j, n-p-j, a[j], d[n-p-j])
        temp = a[j] + d[n-p+j]
        c = 0
        for _ in range(i):
            if w[c][0] >= 0:
                break
            if w[c][1] < j or w[c][1] > n-p-j:
                temp -= w[c][0]
            c += 1
        ans = max(temp, ans)

print(ans)

Submission status: Runtime Error

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

for i in range(min(n,k)+1):
    for j in range(min(n,k)-i+1):
        d=k-i-j
        l=v[0:i]
        r=v[n-j:n]
        p=r+l
        q=[]
        s=sum(p)
        for x in p:
            if x<0:
                q.append(x)
        q.sort()
        for x in range(d):
            s-=q[x]
        ans.append(s)
        
print(max(ans))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
ans=[]
for i in range(len(v)-1):
    for j in range(k-i):
        sum=0
        put=[]
        for K in range(i):
            sum+=v[K]
            put.append(v[K])
        for l in range(len(v)-1,len(v)-j,-1):
            sum+=v[l]
            put.append(v[l])
        put.sort()
        for l in range(k-i-j):
            if(len(put)-1>=l):
                sum-=put[l]
        ans.append(sum)
print(max(ans))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
ans=[]
for i in range(len(v)-1):
    for j in range(len(v)-1-i):
        sum=0
        put=[]
        for K in range(i):
            sum+=v[K]
            put.append(v[K])
        for l in range(len(v)-1,len(v)-1-j,-1):
            sum+=v[l]
            put.append(v[l])
        put.sort()
        for l in range(k-i-j):
            if(len(put)-1>=l):
                sum-=put[l]
        ans.append(sum)
print(max(ans))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
ans=[]
for i in range(len(v)-1):
    for j in range(k-i):
        sum=0
        put=[]
        for K in range(i):
            sum+=v[K]
            put.append(v[K])
        for l in range(len(v)-1,len(v)-1-j,-1):
            sum+=v[l]
            put.append(v[l])
        put.sort()
        for l in range(k-i-j):
            if(len(put)-1>=l):
                sum-=put[l]
        ans.append(sum)
print(max(ans))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
ans=[]
for i in range(k):
    for j in range(k-i):
        sum=0
        put=[]
        for K in range(i):
            sum+=v[K]
            put.append(v[K])
        for l in range(len(v)-1,len(v)-1-j,-1):
            sum+=v[l]
            put.append(v[l])
        put.sort()
        for l in range(k-i-j):
            if(len(put)-1>=l):
                sum-=put[l]
        ans.append(sum)
print(max(ans))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
ans=[]
for i in range(k):
    for j in range(k-i):
        sum=0
        put=[]
        for K in range(i):
            sum+=v[K]
            put.append(v[K])
        for l in range(len(v)-1,len(v)-1-j,-1):
            sum+=v[l]
            put.append(v[l])
        put.sort
        for l in range(k-i-j):
            if(len(put)-1>l):
                sum-=put[l]
        ans.append(sum)
print(max(ans))

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
V = list(map(int,input().split()))
rV = V[::-1]
Q = []
m = min(n,k)
res = 0
for i in range(m+1):
    for j in range(m-i+1):
        Q.extend(V[:i])
        Q.extend(rV[:j])
        if not Q:
            continue
        s = sum(Q)
        Q.sort()
        for k in range(min(i+j+1,m-i-j)):
            if Q[k] < 0:
                s -= Q[k]   
        res = max(res,s)
        Q = []
print(res)

Submission status: Runtime Error

Solution code:
n,k = map(int,input().split())
V = list(map(int,input().split()))
rV = V[::-1]
Q = []
m = min(n,k)
res = 0
for i in range(m+1):
    for j in range(m-i+1):
        Q.extend(V[:i])
        Q.extend(rV[:j])
        if not Q:
            continue
        s = sum(Q)
        Q.sort()
        for k in range(min(i+j+1,m-i-j+1)):
            if Q[k] < 0:
                s -= Q[k]   
        res = max(res,s)
        Q = []
print(res)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import sys
import copy
import collections
from bisect import bisect_left
from bisect import bisect_right
	
def main():
	N, K = map(int, input().split(" "))
	V = list(map(int, input().split(" ")))
	
	ans = 0
	for L in range(K+1):
		for R in range((K+1)-L):
			gets = []
			tmp = 0
			
			for i in range(L):
				tmp += V[i]
				if V[i] < 0:
					gets.append(V[i])
					
			for i in range(R):
				tmp += V[-(i+1)]
				if V[-(i+1)] < 0:
					gets.append(V[-(i+1)])
					
			#print(gets)
			for i in range(K-L-R):
				if len(gets) == 0:
					break
				gets.sort()
				tmp = tmp + (-1 * gets.pop(0))
				
			if tmp > ans:
				ans = tmp
				
	print(ans)
	
	
	
if __name__ == "__main__":
	main()

Submission status: Runtime Error

Solution code:
import sys;input=sys.stdin.readline
from bisect import*

n,q=map(int,input().split())
event=[]
stopped=set([-1])

def doevent(l):
    global stopped
    if l[1]==1:
        if stopped=={-1}:
            stopped=set()
        stopped.add(l[2])
    elif l[1]==-1:
        stopped.remove(l[2])
        if len(stopped)==0:
            stopped={-1}
            
for i in range(n):
    s,t,x=map(int,input().split())
    event.append((s-x,1,x))
    event.append((t-x,-1,x))
event.append((-float("inf"),"x","x"))
event.append((float("inf"),"x","x"))
event.sort(key=lambda x:x[0])
eventtime=[i[0]for i in event]
#print(eventtime)
query=[bisect_right(eventtime,int(input()))-1 for i in range(q)]+[float("inf")]
#print(query)
c=0
#print(event)
for i in range(2*n+1):
    doevent(event[i])
    while i==query[c]:
        print(min(stopped))
        c+=1
        if c==q:
            break

Submission status: Runtime Error

Solution code:
from collections import deque, _heapq
N, K = map(int, input().split())
V = deque(map(int, input().split()))

class Money:
    def __init__(self):
        self.yen = 0
        self.red = []

    def value(self):
        return self.yen + sum(self.red)

    def add(self, yen):
        if yen >= 0:
            self.yen += yen
        else:
            self.red.append(yen)

    def remove(self, yen):
        if yen >= 0:
            self.yen -= yen
        else:
            self.red.remove(yen)

#mny = Money()
def get(cnt, mny, lstop, rstop):
    ans = mny.value()

    if cnt <= 0:
        return ans

    if len(V) > 0:

        if lstop == 0:
            w = V.popleft()
            mny.add(w)
            ans = max(ans, get(cnt-1, mny, lstop, rstop))
            mny.remove(w)
            V.appendleft(w)
        elif lstop > 0:
            lstop -= 1

        if rstop == 0:
            w = V.pop()
            mny.add(w)
            ans = max(ans, get(cnt-1, mny, -1, rstop))
            mny.remove(w)
            V.append(w)

    if len(mny.red) >= cnt // 2:
        w = min(mny.red)
        mny.red.remove(w)

        V.appendleft(w)
        ans = max(ans, get(cnt-1, mny, -1, rstop))
        V.popleft()

        V.append(w)
        ans = max(ans, get(cnt-1, mny, lstop, -1))
        V.pop()

        mny.red.append(w)    

    return ans

print(get(K, Money(), 0, 0))

Submission status: Runtime Error

Solution code:
from collections import deque, _heapq
N, K = map(int, input().split())
V = deque(map(int, input().split()))

class Money:
    def __init__(self):
        self.yen = 0
        self.red = []

    def value(self):
        return self.yen + sum(self.red)

    def add(self, yen):
        if yen >= 0:
            self.yen += yen
        else:
            self.red.append(yen)

    def remove(self, yen):
        if yen >= 0:
            self.yen -= yen
        else:
            self.red.remove(yen)

#mny = Money()
def get(cnt, mny, lstop, rstop):
    ans = mny.value()

    if cnt <= 0:
        return ans

    if len(V) > 0:

        if lstop == 0:
            w = V.popleft()
            mny.add(w)
            ans = max(ans, get(cnt-1, mny, lstop, rstop))
            mny.remove(w)
            V.appendleft(w)
        elif lstop > 0:
            lstop -= 1

        if rstop == 0:
            w = V.pop()
            mny.add(w)
            ans = max(ans, get(cnt-1, mny, -1, rstop))
            mny.remove(w)
            V.append(w)

    if len(mny.red) >= cnt-1:
        w = min(mny.red)
        mny.red.remove(w)

        V.appendleft(w)
        ans = max(ans, get(cnt-1, mny, -1, rstop))
        V.popleft()

        V.append(w)
        ans = max(ans, get(cnt-1, mny, lstop, -1))
        V.pop()

        mny.red.append(w)    

    return ans

print(get(K, Money(), 0, 0))

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;
#define sorted(vector) sort(vector.begin(),vector.end())
#define vmax(vector) *max_element(vector.begin(),vector.end())
#define vsum(vector) accumulate(vector.begin(),vector.end(),0)
#define append(a) push_back(a)
#define int(a) stoi(a)
#define str(a) to_string(a)


int main(void){
    int n,k,tmp;
    vector<int> v,motimono,ans;
    cin>>n>>k;
    for(int i=0  ;i<n  ;i++){
        cin>>tmp;
        v.push_back(tmp);
    }
    
    
    if (k>=n){
        k-=n;
        ans.append(vsum(v));
        sorted(v);
        for(int i=0  ;i<k  ;i++){
            for(int j=0  ;j<min<unsigned long>(k,v.size())  ;i++){
                v[j]=0;
                ans.append(vsum(v));
            }
        }
    }else{
        for(int i=0  ;i<n  ;i++){
            v.append(v[i]);
        }
        for(int j=1  ;j<k+1  ;j++){  //長さ
            for(int i=n-j  ;i<n+1  ;i++){ //開始index
                vector<int> motimono;
                for(int r=i  ;r<i+j  ;r++){
                    motimono.append(v[r]);
                }
                ans.append(vsum(motimono));
                sorted(motimono);
                for(int i=0  ;i< min<unsigned long>(k-j,motimono.size())  ;i++){
                    motimono[i]=0;
                    ans.append(vsum(motimono));
                }
            }
        }
    }
    cout<<vmax(ans)<<endl;
}

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
*v,=map(int,input().split())
motimono=[]
ans=[]
if k>=n:
    k-=n
    ans.append(sum(v))
    v.sort()
    for i in range(k):
        v[i]=0
        ans.append(sum(v))
    
    print(max(ans))
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))
            motimono.sort()
            for i in range(min(k-j,len(motimono))):
                motimono[i]=0
                ans.append(sum(motimono))
    print(max(ans))

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
*v,=map(int,input().split())
motimono=[]
ans=[]
if k>=n:
    k-=n
    heapify(v)
    ans.append(sum(v))
    v.sort()
    for i in range(k):
        v[i]=0
        ans.append(sum(v))
    
    print(max(ans))
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))
            motimono.sort()
            for i in range(min(k-j,len(motimono))):
                motimono[i]=0
                ans.append(sum(motimono))
    print(max(ans))

Submission status: Runtime Error

Solution code:

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

start = N-1


for i in range(K):
    maxSum = V[start]+ V[i]
    ans.append(maxSum)
    if maxSum < 0 : 
       maxSum = 0
       continue
       
       maxSum = max(maxSum, V[start]+ V[i]); 
     
       start  -= 1

print(max(ans))