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:
import itertools
import numpy as np

def main():
	N, K = map(int,input().split())

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

	allCandidates = []
	for i in range(int(K / 2) + 1):
		for one in range(0, K - i + 1):
			allCandidates.extend([[0] * one + [1] * (K - i - one) + [-1] * i])

	maxScore = 0
	for candidate in allCandidates:
		have = []
		zeroCount = 0
		oneCount = 0
		for k in candidate:
			if k == 0:
				try:
					have.append(Vs[0 + zeroCount])
					zeroCount += 1
				except:
					continue
			if k == 1:
				try:
					have.append(Vs[-1 - oneCount])
					oneCount += 1
				except:
					continue
			if k == -1:
				del have[np.argmin(have)]
		score = sum(have)

		if score > maxScore:
			maxScore = score
	print(maxScore)



if __name__ == '__main__':
	main()

Submission status: Runtime Error

Solution code:
import itertools
import numpy as np

def main():
	N, K = map(int,input().split())

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

	allCandidates = []
	for i in range(int(K / 2) + 1):
		for one in range(0, K - i + 1):
			allCandidates.extend([[0] * one + [1] * (K - i - one) + [-1] * i])

	maxScore = 0
	for candidate in allCandidates:
		have = []
		zeroCount = 0
		oneCount = 0
		for k in candidate:
			if k == 0:
				have.append(Vs[0 + zeroCount])
				zeroCount += 1
			if k == 1:
				have.append(Vs[-1 - oneCount])
				oneCount += 1
			if k == -1:
				del have[np.argmin(have)]
		score = sum(have)

		if score > maxScore:
			maxScore = score
	print(maxScore)



if __name__ == '__main__':
	main()

Submission status: Runtime Error

Solution code:
#ABC128D-equeue.py

from sys import stdin

input = stdin.readline

N, K = list(map(int, input().split()))
VList = list(map(int, input().split()))
sumList = []

for i in range(K+1):
    for j in range(K-i+1):
        k = K -i -j
        myHand = [VList[n] for n in range(i)] + [VList[-m] for m in range(1,j+1)] + [0]
        myHand.sort(reverse=True)
        for _ in range(k):
            if myHand[-1] < 0:
                myHand.pop()
            else:
                break
        sumList.append(sum(myHand))


print(max(sumList))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Mon May 27 22:13:19 2019

@author: Yamazaki Kenichi
"""

N, M = map(int,input().split())
ks = [list(map(int,input().split())) for i in range(M)]
p = list(map(int,input().split()))

S = [0 for i in range(M)]
for i in range(M):
    for j in range(1,ks[i][0]+1):
        S[i] += 2**(ks[i][j]-1)

ans = 0
for bit in range(1<<N):
    now = [0 for i in range(M)]
    for i in range(N):
        if bit & 1<<i:
            for j in range(M):
                now[j] += S[j]//(1<<i)
    flg = True
    for j in range(M):
        if now[j]%2 != p[j]:
            flg = False
    ans += flg
print(ans)

Submission status: Runtime Error

Solution code:
from functools import reduce

def get_sum(arr):
    _arr = arr[:]
    if len(_arr) == 1:
        return _arr[0]
    elif len(_arr) == 0:
        return 0
    return reduce(add_num, _arr)

def add_num(a, b):
    return int(a) + int(b)

def append_and_sort(l, v):
    _l = l[:]
    _l.append(v)
    _l.sort()
    return _l

def insert_value(l, v, i):
    _l = l[:]
    _l.insert(i, v)
    return _l

n, k = map(lambda x: int(x), input().split(' '))

v = list(map(lambda x: int(x), input().split(' ')))

def check(current, count, arr):
    if count == 0:
        return get_sum(current)
    
    # result3, result4 = 0, 0
    if current and  count <= len([_v for _v in current if _v < 0]):
        result1 = check(current[1:], count - 1, insert_value(arr, current[0], 0))
        result2 = check(current[1:], count - 1, insert_value(arr, current[0], len(arr)))
    else:
        result1 = check(append_and_sort(current, arr[0]), count - 1, arr[1:])
        result2 = check(append_and_sort(current, arr[-1]), count - 1, arr[:-1])
    
    return max(result1, result2)

print(check([], k, v))

Submission status: Runtime Error

Solution code:
from functools import reduce

def get_sum(arr):
    _arr = arr[:]
    if len(_arr) == 1:
        return _arr[0]
    elif len(_arr) == 0:
        return 0
    return reduce(add_num, _arr)

def add_num(a, b):
    return int(a) + int(b)

def append_and_sort(l, v):
    _l = l[:]
    _l.append(v)
    _l.sort()
    return _l

def insert_value(l, v, i):
    _l = l[:]
    _l.insert(i, v)
    return _l

n, k = map(lambda x: int(x), input().split(' '))

v = list(map(lambda x: int(x), input().split(' ')))

def check(current, count, arr):
    if count == 0:
        return get_sum(current)
    
    # result3, result4 = 0, 0
    if current and  count <= len([_v for _v in current if _v < 0]):
        result1 = check(current[1:], count - 1, insert_value(arr, current[0], 0))
        result2 = check(current[1:], count - 1, insert_value(arr, current[0], len(arr)))
    else:
        result1 = check(append_and_sort(current, arr[0]), count - 1, arr[1:])
        result2 = check(append_and_sort(current, arr[-1]), count - 1, arr[:-1])
    
    return max(result1, result2, result3, result4)

print(check([], k, v))

Submission status: Runtime Error

Solution code:
from functools import reduce

def get_sum(arr):
    _arr = arr[:]
    if len(_arr) == 1:
        return _arr[0]
    elif len(_arr) == 0:
        return 0
    return reduce(add_num, _arr)


def add_num(a, b):
    return int(a) + int(b)

def append_and_sort(l, v):
    _l = l[:]
    _l.append(v)
    _l.sort()
    return _l

def insert_value(l, v, i):
    _l = l[:]
    _l.insert(i, v)
    return _l

n, k = map(lambda x: int(x), input().split(' '))

v = list(map(lambda x: int(x), input().split(' ')))

def check(current, count, arr):
    if count == 0:
        return get_sum(current)
    
    result3, result4 = 0, 0
    result0 = check(current, count - 1, arr)
    result1 = check(append_and_sort(current, arr[0]), count - 1, arr[1:])
    result2 = check(append_and_sort(current, arr[-1]), count - 1, arr[:-1])
    if current and  count <= len([_v for _v in current if _v < 0]):
        result3 = check(current[1:], count - 1, insert_value(arr, current[0], 0))
        result4 = check(current[1:], count - 1, insert_value(arr, current[0], len(arr)))
    
    return max(result0, result1, result2, result3, result4)

print(check([], k, v))

Submission status: Runtime Error

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],]
  tmp=[sorted(item) for item in tmp if any([g>0 for g in item])]
  #print(n,tmp)
  if n!=0:
    for num_remove in range(n):
      tmp2=[item[n:] for item in tmp 
            if all([g<0 for g in item[:n]])
           ]
      
      tmp.extend(tmp2)
      #print("tmp",tmp)
      #print("tmp2",tmp2)
      
  have.extend(tmp)
  #print(n,have[-1])
  
print(max(list(map(sum,have
                  )
              )
         )
     )

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
ns = lambda: sys.stdin.readline().rstrip()
ni = lambda: int(ns())
nm = lambda: map(int, sys.stdin.readline().split())
nl = lambda: list(nm())
nsm = lambda: map(str, sys.stdin.readline().split())

n, k = nm()
v = nl()
d = deque(v)
ans = 0
for m in range(k + 1):
    for p in range(m + 1):
        lis = copy.copy(d)
        neg = []
        summ = 0
        for i in range(p):
            if len(lis) == 0:
                break
            l = lis.popleft()
            summ += l
            if l < 0:
                neg.append(l)
        for j in range(m - p):
            if len(lis) == 0:
                break
            l = lis.pop()
            summ += l
            if l < 0:
                neg.append(l)
        neg.sort()
        for o in range(k - m):
            if o < len(neg):
                summ -= neg[o]
            else:
                break
        ans = max(ans, summ)
print(ans)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
ns = lambda: sys.stdin.readline().rstrip()
ni = lambda: int(ns())
nm = lambda: map(int, sys.stdin.readline().split())
nl = lambda: list(nm())
nsm = lambda: map(str, sys.stdin.readline().split())

n, k = nm()
v = nl()
d = deque(v)
ans = 0
for m in range(k + 1):
    for p in range(m + 1):
        lis = d.copy()
        neg = []
        summ = 0
        for i in range(p):
            if len(lis) == 0:
                break
            l = lis.popleft()
            summ += l
            if l < 0:
                neg.append(l)
        for j in range(m - p):
            if len(lis) == 0:
                break
            l = lis.pop()
            summ += l
            if l < 0:
                neg.append(l)
        neg.sort()
        for o in range(k - m):
            if o < len(neg):
                summ -= neg[o]
            else:
                break
        ans = max(ans, summ)
print(ans)

Submission status: Runtime Error

Solution code:
N, K = map(int,input().split())
V = list(map(int,input().split()))
L,R = [0]*(K),[0]*(K)
L[0] = max(0,V[0])
R[0] = max(0,V[-1])
for i in range(min(N,K)+1):
    part = V[:i]
    part.sort()
    for j in range(min(K-i,i)):
        if part[0] < 0:
            part.pop(0)
        L[i+j] = max(L[i+j],sum(part))
V.reverse()
for i in range(min(N,K)+1):
    part = V[:i]
    part.sort()
    for j in range(min(K-i,i)):
        if part[0] < 0:
            part.pop(0)
        R[i+j] = max(R[i+j],sum(part))
R[-1] = max(0,sum(part())
ans = max(R[-1],L[-1])
for i in range(K-1):
    ans = max(ans,L[i]+R[-i-2])
print(L)
print(R)
print(ans)

Submission status: Runtime Error

Solution code:
#include <iostream>
#include <queue>

#define MAX_N 50

using namespace std;

int N, K;
int V[MAX_N];

int main( int argc, char **argv )
{
    // input
    cin >> N >> K;

    for ( int i = 0; i < N; i++ ) cin >> V[i];

    // solve
    long long ans = 0;
    int R = min( N, K );
    for ( int A = 0; A <= R; A++ )
    {
        for ( int B = 0; B <= R - A; B++ )
        {
            priority_queue<int> que;
            for ( int i = 0; i < A; i++ ) que.push( -V[i] );
            for ( int i = 0; i < B; i++ ) que.push( -V[N - 1 - i] );

            long long sum = 0;
            int throwAwayNum = 0;
            while ( !que.empty() )
            {
                int x = -que.top();
                que.pop();

                if ( x < 0 && A + B + throwAwayNum < R )
                    throwAwayNum++;
                else
                    sum += x;
            }
            ans = max( ans, sum );
        }
    }

    cout << ans << endl;

    return 0;
}

Submission status: Runtime Error

Solution code:
import math
import numpy as np


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


def main():
    N, K = inputs()
    D = inputs()
    ans = []
    cnt = 0
    for i in range(K):
        index = np.argmax(D)
        MAX = D[index]
        if MAX < 0:
            break
        else:
            if N / 2 > index:
                v = D.pop(0)
            else:
                v = D.pop()
            if v < 0:
                cnt += 1
            ans.append(v)
        if cnt + i + 1 >= K:
            break
        # print(ans, cnt + i + 1)
    ans.sort()
    # print(ans)
    for i in range(cnt):
        ans.pop(0)

    print(max(sum(ans), 0))


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import heapq
N,K = map(int, input().split())
*V, = map(int, input().split())
#N, K = 6, 4
#V = [-10, 8, 2, 1, 2, 6]
motimono = []
ans = []

if K >= N: # 操作回数のほうが大きいなら、全部取り出してから何個戻すかを考える
    K -= N
    heapq.heapify(V)
    ans.append(sum(V))
    for i in range(K):
        if len(V)>0:
            heapq.heappop(V)
        ans.append(sum(V))
    print(max(ans))

else:
    V *= 2 # 前後からの取り出しを楽にするためにこうしておく
    #print(V)
    for j in range(1,K+1): # 取り出す個数
        for i in range(N-j, N+1): # 何番目から取り出すか
            motimono = V[i:i+j]
            #print(str(j), str(i), motimono)
            ans.append(sum(motimono))
            #print(ans)
            heapify(motimono)
            for i in range(K-j): # 戻す個数
                if len(motimono)>0:
                    heappop(motimono)
                ans.append(sum(motimono))
    print(max(ans))

Submission status: Runtime Error

Solution code:
import heapq
#N,K = map(int, input().split())
#*V, = map(int, input().split())
N, K = 6, 4
V = [-10, 8, 2, 1, 2, 6]
motimono = []
ans = []

if K >= N: # 操作回数のほうが大きいなら、全部取り出してから何個戻すかを考える
    K -= N
    heapq.heapify(V)
    ans.append(sum(V))
    for i in range(K):
        if len(V)>0:
            heapq.heappop(V)
        ans.append(sum(V))
    print(max(ans))

else:
    V *= 2 # 前後からの取り出しを楽にするためにこうしておく
    #print(V)
    for j in range(1,K+1): # 取り出す個数
        for i in range(N-j, N+1): # 何番目から取り出すか
            motimono = V[i:i+j]
            #print(str(j), str(i), motimono)
            ans.append(sum(motimono))
            #print(ans)
            heapify(motimono)
            for i in range(K-j): # 戻す個数
                if len(motimono)>0:
                    heappop(motimono)
                ans.append(sum(motimono))
    print(max(ans))

Submission status: Runtime Error

Solution code:
def count_l(d,n):
	maxim = 0
	if n > 0:
		for t in wa_l(d,n-1):
			maxim = max(t[0]+d[t[1]],maxim)
	return(maxim)

def count_r(d,n):
	maxim = 0
	if n > 0:
		for t in wa_r(d,n-1):
			maxim = max(t[0]+d[N-1-t[1]],maxim)
	return(maxim)			
		

def wa_l(d,n):
	if n == 0:
		return([[0,0]])
	if n == 1:
		return([[d[0],1]])
	if n == 2:
		return([[0,1],[d[0]+d[1],2]])
	if n > 2:
		a = []
		for j in wa_l(d,n-2):
			j[1] += 1
			a.append(j)
		for j in wa_l(d,n-1):
			j[0] += d[j[1]]
			j[1] += 1
			a.append(j)
		return(a)

def wa_r(d,n):
	if n == 0:
		return([[0,0]])
	if n == 1:
		return([[d[N-1],1]])
	if n == 2:
		return([[0,1],[d[N-1]+d[N-2],2]])
	if n > 2:
		a = []
		for j in wa_r(d,n-2):
			j[1] += 1
			a.append(j)
		for j in wa_r(d,n-1):
			j[0] += d[N-1-j[1]]
			j[1] += 1
			a.append(j)
		return(a)

def l_r(d,n):
	maxim = 0
	for x in range(n+1):
		maxim = max(count_r(d,x)+count_l(d,n-x),maxim)
	print(maxim)

N, q= map(int,input().split())
p = list(map(int,input().split()))

l_r(p,q)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;

int calc(vector<int> V, int a, int b, int k){
    vector<int> v;
    if( a == 0){
        if (b > 0)
            v = vector<int>(V.end() - b, V.end());
        else
            return 0;
    }
    else{
        v = vector<int>(V.begin(), V.begin() + a);
        if (b > 0)
            v.insert( v.end(), V.end() - b, V.end());
    }
    sort(v.begin(), v.end());
    int res = 0;
    int p = -1;
    int t = min(a + b, k - a - b);
    for(int i = 0; i < t; i++){
        if (v.at(i) > 0){
            p = i;
            break;
        }
    }
    if(p == -1){
        if (a + b > t)
            p = t;
        else
            return 0;
    }

    for(int i = p; i < a + b; i++){
        res += v.at(i);
    }
    return res;
}

int main() {
    int N, K;
    cin >> N >>K;
    vector<int> V(N);
    for (int i = 0; i < N; i++){
        cin >> V[i];
    }

    int r = min(N, K);
    int ans = 0;
    for(int a = 0; a < r; a++){
        for(int b = 0; b < r - a; b++){
            int res = calc(V, a, b, K);
            if(ans < res)
                ans = res;
        }
    }
    cout << ans << endl;
}

Submission status: Runtime Error

Solution code:
def handPop(hand):
    min_val = hand.pop(hand.index(min(hand)))
    return hand, min_val

N, K = map(int, input().split())
V = list(map(int, input().split()))
hand = []
ps = []
def func(V, hand, K):
    if K < 1:
        ps.append(hand)
        return
    if len(hand) > 0 and min(hand) < 0:
        hand_ = hand[:]
        hand_, min_val = handPop(hand_)
        C = func([min_val] + V, hand_, K-1)
        D = func(V + [min_val], hand_, K-1)
        A = func(V[1:], hand+[V[0]], K-1)
        B = func(V[:-1], hand+[V[-1]], K-1)
    else:
        A = func(V[1:], hand+[V[0]], K-1)
        B = func(V[:-1], hand+[V[-1]], K-1)

    
func(V, hand, K)
v_max = max([sum(x) for x in ps])
print(v_max if v_max > 0 else 0)

Submission status: Runtime Error

Solution code:
from itertools import islice
 
R = lambda: map(int, input().split())
n, k = R()
v = list(R())
a = sorted((x, i) for i, x in enumerate(v) if x < 0)
ans = max(sum(v[:i - j] + v[n - j:])) -
          sum(islice((x for x, m in a if m < i - j or m >= n - j), k - i))
          for i in range(1, min(n, k) + 1) for j in range(i))
print(ans)

Submission status: Runtime Error

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

ans = - 10**7
for i in range(min(N,K)+1):
  for j in range(min(N,K)+1-i
    if j == 0:
      st = A[:i]
    else:
      st = A[:i]+ A[-j:]
    st.sort(reverse = 1)):
    for suteru in range(K - i - j):
      ans = max(ans, sum(st[:i+j-suteru]))
    
print(ans)

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
R=min(N,K)
L=[]
for r in range(R+1):
    for A in range(R -r + 1):
        B = R - r-A
        I = sorted((V[:A] + V[::-1][:B]))
        p=K-A-B
        for i in range(len(I)):
            if I[i] >= 0:
                p = i
                break
        for ii in range(min(p,K-A-B)):
            if len(I)>0:
                I.pop(0)
            else:break
            L.append(sum(I))
print(max(L))

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
R=min(N,K)
L=[]
for r in range(R+1):
    for A in range(R -r + 1):
        B = R - r-A
        I = sorted((V[:A] + V[::-1][:B]))
        for i in range(len(I)):
            p=K-A-B
            if I[i] >= 0:
                p = i
                break
        for ii in range(min(p,K-A-B)):
            while len(I)>0:
                I.pop(0)
            L.append(sum(I))
print(max(L))

Submission status: Runtime Error

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

Lvalue = [[0 for _ in range(K)] for i in range(K)]
Rvalue = [[0 for _ in range(K)] for i in range(K)]

for i in range(K):
    Lvalue[i][i] = sum(V[:(i+1)])
    for n in range(i+1):
        if V[n] < 0:
            Neg.append(V[n])
        Neg.sort()
    for j in range(K-i-1):
        if Neg != []:
            Lvalue[i][i+j+1] = Lvalue[i][i+j] - Neg[0]
            Neg.pop(0)
        else:
            Lvalue[i][i + j + 1] = Lvalue[i][i+j]


V = V[::-1]

Neg = []
for i in range(K):
    Rvalue[i][i] = sum(V[:(i+1)])
    for n in range(i+1):
        if V[n] < 0:
            Neg.append(V[n])
        Neg.sort()
    for j in range(K-i-1):
        if Neg != []:
            Rvalue[i][i+j+1] = Rvalue[i][i+j] - Neg[0]
            Neg.pop(0)
        else:
            Rvalue[i][i + j + 1] = Rvalue[i][i+j]

Lmax = [0 for i in range(K+1)]
Rmax = [0 for i in range(K+1)]

for i in range(K):
    for j in range(K):
        lmax = Lvalue[j][i]
        if Lmax[i+1] < lmax:
            Lmax[i+1] = lmax

for i in range(K):
    for j in range(K):
        rmax = Rvalue[j][i]
        if Rmax[i+1] < rmax:
            Rmax[i+1] = rmax

record = 0
for i in range(K+1):
    for j in range(K+1-i):
        score1 = Lmax[i]+Rmax[j]
        score2 = Lmax[j]+Rmax[i]
        S = max(score1,score2)
        if record < S:
            record = S

print(record)

Submission status: Runtime Error

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

    m = 0

    r = min(N, K)
    for a in range(r+1):
        for b in range(r+1-a):
            if b == 0:
                v = V[:a]
            else:
                v = V[:a] + V[-b:]
            v.sort()    
            for i in range(K-a-b):
                if v[i] >= 0:
                    break
            s = sum(v[i:])
            if s > m:
                m = s

    print(m)


main()

Submission status: Runtime Error

Solution code:
from collections import deque

N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
O = min(N, K)
for i in range(O+1):
    for j in range(O-i+1):
        if i + j > O:
            break
        DV = deque(V)
        S = 0
        nums = []
        for _ in range(i):
            nums.append(DV.popleft())
        for _ in range(j):
            nums.append(DV.pop())
        nums.sort()
        for n in range(min(K-i-j, len(nums))):
            if nums[n] >= 0:
                break
            del nums[n]
        ans = max(ans, sum(nums))
print(ans)

Submission status: Runtime Error

Solution code:
from functools import reduce

def get_sum(arr):
    if isinstance(arr, int):
        return arr
    _arr = arr[:]
    if len(_arr) > 1:
        return reduce(add_num, _arr)
    elif len(_arr) == 1:
        return _arr[0]
    elif len(_arr) == 0:
        return 0
    return -1000

def add_num(a, b):
    return int(a) + int(b)

def append_and_sort(l, v):
    _l = l[:]
    _l.append(v)
    _l.sort()
    return _l

def insert_value(l, v, i):
    _l = l[:]
    _l.insert(i, v)
    return _l

n, k = map(lambda x: int(x), input().split(' '))

v = list(map(lambda x: int(x), input().split(' ')))

def check(current, count, arr):
    if count == 0:
        return current
    
    result3, result4 = [], []
    result0 = check(current, count - 1, arr)
    result1 = check(append_and_sort(current, arr[0]), count - 1, arr[1:])
    result2 = check(append_and_sort(current, arr[-1]), count - 1, arr[:-1])
    if current and any([value < 0 for value in current]):
        result3 = check(current[1:], count - 1, insert_value(arr, current[0], 0))
        result4 = check(current[1:], count - 1, insert_value(arr, current[0], len(arr)))
    
    return max(get_sum(result0), get_sum(result1), get_sum(result2), get_sum(result3), get_sum(result4))

print(check([], k, v))

Submission status: Runtime Error

Solution code:
import heapq
from itertools import chain

R = lambda: map(int, input().split())
n, k = R()
v = list(R())
r = 0
for i in range(min(n, k)):
    for j in range(i):
        s = 0
        h = []
        for m in chain(range(i - j), range(n - j, n)):
            x = v[m]
            s += x
            if x < 0:
                heapq.heappush(h, x)
        while h and i < k:
            s -= heapq.heappop(h)
            i += 1
        r = max(r, s)
print(r)

Submission status: Runtime Error

Solution code:
from functools import reduce

def get_sum(arr):
    if isinstance(arr, int):
        return arr
    _arr = arr[:]
    if len(_arr) > 1:
        return reduce(add_num, _arr)
    elif len(_arr) == 1:
        return _arr[0]
    return -1000

def add_num(a, b):
    return int(a) + int(b)

def append_and_sort(l, v):
    _l = l[:]
    _l.append(v)
    _l.sort()
    return _l

def insert_value(l, v, i):
    _l = l[:]
    _l.insert(i, v)
    return _l

n, k = map(lambda x: int(x), input().split(' '))

v = list(map(lambda x: int(x), input().split(' ')))

def check(current, count, arr):
    if count == 0:
        return current
    
    result3, result4 = [], []
    result1 = check(append_and_sort(current, arr[0]), count - 1, arr[1:])
    result2 = check(append_and_sort(current, arr[-1]), count - 1, arr[:-1])
    if current and any([value < 0 for value in current]):
        result3 = check(current[1:], count - 1, insert_value(arr, current[0], 0))
        result4 = check(current[1:], count - 1, insert_value(arr, current[0], len(arr)))
    
    return max(get_sum(result1), get_sum(result2), get_sum(result3), get_sum(result4))

print(check([], k, v))

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
input = sys.stdin.readline

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

for i in range(K+1): #左から
    for j in range(K-i+1): #右から
        hand = deque()
        for n in range(i): #左から
            hand.append(V[n]) 
        for m in range(j): #右から
            hand.append(V[N-m-1])
        for k in range(K-i-j):
            if len(hand) > 0 and min(hand) < 0:
                hand.remove(min(hand)) 
        score.append(sum(hand))

print(max(score))

Submission status: Runtime Error

Solution code:
from itertools import accumulate


def make_dp(vvv, n, k):
    dp = [-(10 ** 9) * (k + 1)]
    dp[0] = 0

    for i in range(min(n, k)):
        i += 1
        vv = vvv[:i]
        vv.sort(reverse=True)
        sm = sum(vv)
        dp[i] = max(dp[i], sm)
        while i < k and vv and vv[-1] < 0:
            sm -= vv.pop()
            i += 1
            dp[i] = max(dp[i], sm)

    return list(accumulate(dp, func=max))


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

acl = make_dp(vvv, n, k)
acr = make_dp(reversed(vvv), n, k)

ans = max(acl[i] + acr[k - i] for i in range(k + 1))
ans = min(ans, sum(v for v in vvv if v > 0))
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
from copy import deepcopy

length,kaisu=map(int,input().split())
A=deque(map(int,input().split()))
maxhist=[0]
for left in range(kaisu+1):
  for right in range(kaisu-left+1):
    l=deepcopy(A)
    point=[]
    dropable=kaisu-left-right
    for i in range(left):
      num=l.popleft()
      point.append(num)
    for j in range(right):
      num2=l.pop()
      point.append(num2)
    droptime=0
    while(droptime<dropable):
      if point==[]:
        break
      elif min(point)>0:
        break
      else:
        point.sort(reverse=True)
        point.pop(-1)
        droptime+=1
    maxhist.append(sum(point))
print(max(maxhist))

Submission status: Runtime Error

Solution code:
n,k,*v=map(int,open(0).read().split())
m=0
r=range
for i in r(n+1):
 for j in r(min(k,n)-i+1):
  t=sorted(v[:i]+v[-j:]*(j>0))[::-1];c=k-i-j
  while c*t[-1]<0:t.pop();c-=1
  m=max(m,sum(t))
print(m)

Submission status: Runtime Error

Solution code:
# N = int(input())
# A = [int(x) for x in input().split()]
# V = [[0] * 100 for _ in range(100)]

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

import itertools

RV = list(itertools.accumulate(V))

# 左から最大でl個とる
# for l in range(K + 1):
#     # 右からは最大でk-l個
#     for r in range(K + 1 - l):
#         print("l:{}, r:{}".format(l, r))


# heapq.heappush(Q,)
import heapq

from collections import defaultdict


def f(k):
    ret = -99999999999999999999999
    dd = defaultdict(lambda: 0)
    s = 0
    for i in range(k):
        s += V[-k + i]
        dd[V[-k + i]] += 1

    ret = max(ret, s - neg(dd, K - k))

    for i in range(k):
        rm = V[-k + i]
        ad = V[-k + i + k]
        dd[rm] -= 1
        dd[ad] += 1
        s -= rm
        s += ad
        ret = max(ret, s - neg(dd, K - k))
        # print(ret)

    return ret


def neg(d, n):
    L = sorted(d.items())
    ret = 0

    for l in L:
        v, cnt = l[0], l[1]
        if n <= 0 or v >= 0:
            break

        if n >= cnt:
            ret += (v * cnt)
        else:
            ret += (v * n)
        n -= cnt
    return ret


ans = 0
for i in range(1, K + 1):
    ans = max(ans, f(i))
print(ans)

Submission status: Runtime Error

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

ans = 0

for l in range(n):
    for r in range(n-l+1):
        if l+r >k:
            break
        nv = v[:l] + v[n-r:]
        nv.sort()
        for i in range(k-l-r):
            if not nv or nv[0] >= 0:
                break
            nv.pop(0)
        ans = max(ans,sum(nv))
print(ans)

Submission status: Runtime Error

Solution code:
from heapq import heapify, heappop

N, K = map(int, input().split())
vl = list(map(int, input().split()))
vr = list(reversed(vl))
sum_L = [0]
for vv in vl:
    sum_L.append(sum_L[-1] + vv)

sum_R = [0]
for vv in vr:
    sum_R.append(sum_R[-1] + vv)

ans = 0
for pick in range(K + 1):
    put = K - pick
    if pick < put: continue
    for left in range(pick + 1):
        right = pick - left

        t = sum_L[left] + sum_R[right]

        q = vl[:left] + vr[:right]
        heapify(q)

        cnt = 0
        while cnt < put and q:
            x = heappop(q)
            t -= x
            cnt += 1
        ans = max(ans, t)
print(ans)

Submission status: Runtime Error

Solution code:
from heapq import heapify, heappop

N, K = map(int, input().split())
vl = list(map(int, input().split()))
vr = list(reversed(vl))
sum_L = [0]
for vv in vl:
    sum_L.append(sum_L[-1] + vv)

sum_R = [0]
for vv in vr:
    sum_R.append(sum_R[-1] + vv)

ans = 0
for pick in range(K + 1):
    put = K - pick
    if pick < put: continue
    for left in range(pick + 1):
        m_put = put
        right = pick - left
        t = sum_L[left] + sum_R[right]
        q = vl[:left] + vr[:right]
        heapify(q)
        while m_put > 0:
            t -= heappop(q)
            m_put -= 1
        ans = max(ans, t)
print(ans)

Submission status: Runtime Error

Solution code:
import copy

n, k = map(int, input().split())
v = list(map(int, input().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)