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: Accepted

Solution code:
import heapq
from collections import deque

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

res = 0 # 答えの初期値
for i in range(K+1): # 左端から宝石を取り出す回数
    for j in range(K+1-i): # 右端から宝石を取り出す回数
        sub = K - i - j # 価値がマイナスの宝石を捨てる回数
        d = deque(v) # dequeに詰まった宝石
        a = [] # 持っている宝石
        
        # 左端から宝石を取り出す
        cnt = 0
        while (cnt < i) & (len(d) > 0):
            heapq.heappush(a, d.popleft())
            cnt += 1
            
        # 右端から宝石を取り出す
        cnt = 0
        while (cnt < j) & (len(d) > 0):
            heapq.heappush(a, d.pop())
            cnt += 1
        
        # 試行回数が許す限り手持ちの宝石から価値がマイナスのものを捨てる
        # マイナスでない事によるストップ→bを足す、そうでないなら足さない
        b = 0 # 捨てる宝石の価値
        cnt = 0
        while (cnt < sub) & (b <= 0) & (len(a) > 0):
            b = heapq.heappop(a)
            cnt += 1
        value = sum(a) + b if b > 0 else sum(a)
        res = max(res, value)
print(res)

Submission status: Accepted

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

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

ans = 0
try_num = min(N,K)
for i in range(1 , try_num + 1):#pickする回数
    for j in range(i+1):
        pick_list = V[:i-j] + V[N - j:]
        
        rest_try_num = min(K-i , i)
        pick_list = sorted(pick_list) 
        for k in range(rest_try_num):
            if pick_list[k] <0:
                pick_list[k] = 0
            else:
                break

        ans = max(ans , sum(pick_list))

print(ans)

Submission status: Accepted

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

idou=min(n,k)
ans=0

for i in range(idou):
    for j in range(n,n-idou+i,-1):

        A=v[:i+1]
        B=v[j:]
        C=[0 for i in range(k)]
        C+=A+B
        C.sort()
        C=[C[i] for i in range(k-len(A)-len(B))if 0>C[i]]

        #print(A,B,C)

        ans=max(sum(A)+sum(B)-sum(C),ans)

ans=max(sum(v[n-k:]),ans)


print(ans)

Submission status: Accepted

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

retn = 0

k_cap = k
if (k > n):
    k_cap = n

for l in range(k_cap + 1):
    list_mine_l = list_v[:l]

    for r in range(k_cap - l + 1):
        list_mine_r = list_mine_l.copy()
        if (r > 0):
            list_mine_r.extend(list_v[-r:])
        list_mine_r.sort()

        sss = len(list_mine_r)
        if (sss > k-l-r):
            sss = k-l-r
        for s in range(sss + 1):
            list_mine_s = list_mine_r[s:]

            if (len(list_mine_s) > 0):
                tmp = sum(list_mine_s)
                if (retn < tmp):
                    retn = tmp

print(retn)

Submission status: Accepted

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+1):
  for rrr in range(num-lll+1):
    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(min(rest,len(pick))):
      if pick[iii]<0:
        ans-=pick[iii]
    fans=max(ans,fans)
print(fans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-


def main():
    n, k = map(int, input().split())
    v = list(map(int, input().split()))
    reverse_v = v[::-1]
    ans = 0

    # See:
    # https://www.youtube.com/watch?v=m-Nov1EvGoc
    for left in range(k + 1):
        for right in range(k - left + 1):
            if left + right > n:
                continue

            remain = k - (left + right)
            merged_v = sorted(v[:left] + reverse_v[:right])
            merged_v_len = len(merged_v)
            minus = 0

            for i in range(min(remain, merged_v_len)):
                if merged_v[i] < 0:
                    minus += merged_v[i]

            ans = max(ans, sum(merged_v) - minus)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-


def main():
    n, k = map(int, input().split())
    v = list(map(int, input().split()))
    reverse_v = v[::-1]
    ans = 0

    for left in range(k + 1):
        for right in range(k - left + 1):
            if left + right > n:
                continue

            remain = k - (left + right)
            merged_v = sorted(v[:left] + reverse_v[:right])
            merged_v_len = len(merged_v)
            minus = 0

            for i in range(min(remain, merged_v_len)):
                if merged_v[i] < 0:
                    minus += merged_v[i]

            ans = max(ans, sum(merged_v) - minus)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import heapq
N, K = [int(_) for _ in input().split()]
V = [int(_) for _ in input().split()]
ans = 0
for il in range(K + 1):
    for ir in range(K + 1 - il):
        if il + ir > min([N, K]):
            continue
        H = V[:il] + V[N - ir:N]
        heapq.heapify(H)
        now = 0
        for d in range(1, il + ir):
            if il + ir + d > K:
                break
            v = heapq.heappop(H)
            if v >= 0:
                now += v
                break
        now += sum(H)
        ans = max([ans, now])
print(ans)

Submission status: Accepted

Solution code:

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

ans = 0
for sublen in range(1, min(k+1,n+1)):

    for left in range(0, sublen+1):
        right = sublen - left
        subq = vl[:left] + vl[n-right:]
        subq.sort()

        rlen_max = min(k-sublen, len(subq)-1 )
        rlenf = 0
        for rlen in range(rlen_max-1, -1, -1):
            if subq[rlen] <= 0:
                rlenf = rlen + 1
                break

        ans = max(ans, sum(subq[rlenf:]))


print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

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

ans = 0  # 何もしないと0なので、ansの初期値は0


# pick->取り出す操作をする回数(listより多く取り出さないように注意)
for pick in range(min(K+1, N+1)):
    # 右から取り出す数
    for right in range(pick+1):
        left = pick-right  # 左から取り出す数
        pick_list = V[:right]+V[N-left:]

        # queueに戻す操作
        pick_list = sorted(pick_list)
        tmp_ans = sum(pick_list)  # 戻す前の合計値
        rem = min(K-pick, len(pick_list))  # 戻す操作をできる回数
        for i in range(rem):  # 負の値のものをできるだけ戻す
            if pick_list[i] < 0:
                tmp_ans -= pick_list[i]
            else:
                break
        ans = max(tmp_ans, ans)
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

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

ans = 0
for pick in range(min(K+1, N+1)):
    for right in range(pick+1):
        left = pick-right
        tmp_list = V[:right]+V[N-left:]
        tmp_list = sorted(tmp_list)
        tmp_ans = sum(tmp_list)
        rem = min(K-pick, len(tmp_list))
        for i in range(rem):
            if tmp_list[i] < 0:
                tmp_ans -= tmp_list[i]
            else:
                break
        ans = max(tmp_ans, ans)
print(ans)

Submission status: Accepted

Solution code:
import sys, os

f = lambda:list(map(int,input().split()))
if 'local' in os.environ :
    sys.stdin = open('./input.txt', 'r')

def solve():
    n, k = f()
    v = f()

    ans = 0
    for take in range(1, min(k+1, n+1)):
        r_op = k - take
        for left in range(0, take+1):
            right = take - left
            nums = v[:left] + v[n- right:]
            nums = sorted(nums)
            cur_ans = sum(nums) 

            for i in range(r_op):
                if i<len(nums) and nums[i]<0:
                    cur_ans += abs(nums[i])

            ans = max(ans, cur_ans)
    
    print(ans)

            


solve()

Submission status: Accepted

Solution code:
N,K = (int(i) for i in input().split())
V = [int(i) for i in input().split()]
dashi = min([N,K])
result2 = 0
for i in range(dashi + 1):
    modoseru = K - i
    for leftdashi in range(i + 1):
        values = [0]
        for k in range(leftdashi):
            values.append(V[k])
        for J in range(i - leftdashi):
            if J >= 0:
                values.append(V[-1 * J - 1])

        values.sort()
        for n in range(modoseru):
            if len(values) >= 1 and values[0] <= 0:
                values.pop(0)
        result = sum(values)
        if result2 < result:
            result2 = result
            
print(result2)

Submission status: Accepted

Solution code:
def smaller(x, y):
	if x < y: return x
	return y

N, K = map(int, input().split())
V = list(map(int, input().split()))
M = smaller(N, K)
max = 0
for i in range(0, M+1):
	for j in range(0, M+1-i):
		negative = []
		sum = 0
		for k in range(0, i):
			if V[k] < 0: negative.append(V[k])
			sum += V[k]
		for k in range(0, j):
			if V[-1-k] < 0: negative.append(V[-1-k])
			sum += V[-1-k]
		negative.sort()
		for k in range(0, smaller(len(negative), K-i-j)):
			sum -= negative[k]
		if max < sum: max = sum
print(max)

Submission status: Accepted

Solution code:
import sys, heapq, copy
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):
		tmp = 0
		score = 0
		hands = [0] * K
		V = copy.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(max(K - i_rget - i_lget, 0) + 1):
			if i > 0:
				tmp = heapq.heappop(hands)
				if tmp < 0:
					score -= tmp
				else:
					break
		
		if score > max_score:
			max_score = score

print(max_score)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
k = min(N, K)
v = 0
for i in range(k + 1):
    for j in range(k - i + 1):
        v_tmp = V[:i] + V[(N - j):]
        v_tmp.sort()
        for l in range(K - (i + j) + 1):
            v = max(v, sum(v_tmp[l:]))
print(v)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
k = min(N,K)
v = 0
for i in range(k  + 1):
    for j in range(k  - i + 1):
        v_tmp = V[:i] + V[(N - j):]
        v_tmp.sort()
        for l in range(K - (i + j) + 1):
            v = max(v, sum(v_tmp[l:]))
print(v)

Submission status: Accepted

Solution code:
def resolve():
  N, K = list(map(int, input().split()))
  V = list(map(int, input().split()))
  r = 0
  for i in range(min(N,K)+1):
    for j in range(min(N-i,K-i)+1):
      a = V[:i]+V[N-j:]
      b = [x for x in a if x<0]
      b.sort()
      rij = sum(a)-sum(b[:K-i-j])
      r = max(r, rij)
  print(r)
resolve()

Submission status: Accepted

Solution code:
# coding: utf-8

import sys
input = sys.stdin.readline

# N = int(input())
N, K = map(int, input().split())
D = [int(x) for x in input().split()]
# S = input()

ans = 0
for l in range(N + 1):
    if l > K:
        break

    for r in range(N - l + 1):
        if l + r > K:
            break

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

Submission status: Accepted

Solution code:
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-l+1):
    a=[]
    if l+r>N:
      break
    a=V[:l]
    a.extend(V[N-r:])
    b=sum(a)
    a.sort()
    for i in range(min(K-l-r,l+r)):
      if a[i]>=0:
        break
      else:
        b-=a[i]
    ans=max(ans,b)
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
Vlist = list(map(int, input().split()))
ret = 0
for l in range(min(N,K)+1):
    for r in range(min(N,K)-l+1):
        tem = Vlist[:l]+Vlist[N-r:]
        tem = sorted(tem)
        tem[:K-l-r] = [max(0, i) for i in tem[:K-l-r]]
        score = sum(tem)
        if ret < score:
            ret = score
print(ret)

Submission status: Accepted

Solution code:
n,k,*v=map(int,open(0).read().split())
motimono=[]
ans=[]
v*=2
for j in range(1,min(n,k)+1):
    for i in range(n-j,n+1):
        motimono=v[i:i+j]
        ans.append(sum(motimono))
        motimono.sort(reverse=1)
        for i in range(min(k-j,j)):
            del motimono[-1]
            ans.append(sum(motimono))
print(max(ans))

Submission status: Accepted

Solution code:
n,k,*v=map(int,open(0).read().split())
motimono=[]
ans=[]
v*=2
for j in range(1,min(n,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,j)):
            del motimono[0]
            ans.append(sum(motimono))
print(max(ans))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))+[-10**8]
ans=0
for i in range(1,K+1):
    for j in range(1,min(i+1,N+1)):
        W=sorted(V[:j]+V[-min(i,N)-1+j:],reverse=True)[:-1]
        for k in range(0,K-i):
            if W[-1]<0:
                W.pop()
                if W==[]:
                    break
            else:
                break
        if ans<sum(W):
            ans=sum(W)
print(ans)

Submission status: Accepted

Solution code:
from heapq import*
n,k=map(int,input().split())
*v,=map(int,input().split())
motimono=[]
ans=[]
v*=2
for j in range(1,min(n,k)+1):
    for i in range(n-j,n+1):
        motimono=v[i:i+j]
        ans.append(sum(motimono))
        heapify(motimono)
        for i in range(k-j):
            if len(motimono)>0:
                heappop(motimono)
            ans.append(sum(motimono))
print(max(ans))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Wed May 29 22:59:58 2019

@author: Yamazaki Kenichi
"""

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

ans = 0
for pickup_n in range(min(K, N)+1):
    for start in range(pickup_n + 1):
        tmp = [0]
        for i in range(pickup_n):
            tmp.append(V[i - start])
        tmp.sort()
        for i in range(K - pickup_n):
            if tmp[i] < 0:
                tmp[i] = 0
            else:
                break
        ans = max(ans,sum(tmp))
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
v = [int(i) for i in input().split()]
jewel = []
ans = 0
for i in range(min(k+1,n+1)):
  for j in range(min(k-i+1,n-i+1)):
    jewel = v[:i] + v[:-(j+1):-1]
    jewel.sort()
    temp = sum(jewel)
    leng = len(jewel)
    for m in range(k-i-j):
      if leng > m and jewel[m] < 0:
        temp += -jewel[m]
    ans = max(ans,temp)
print(ans)

Submission status: Accepted

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

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

NK_min = min(N, K)

Max = 0
for r in range(NK_min + 1):
    for l in range(NK_min - r + 1):
        rev = K - r - l
        having = None
        if r == 0:
            having = V_lst[:l]
        else:
            having = V_lst[:l] + V_lst[-r:]
        having.sort()
        for _ in range(rev):
            if len(having) == 0:
                break
            if having[0] < 0:
                having.pop(0)
            else:
                break

        if Max < sum(having):
            Max = sum(having)
#        print(r,l,rev,Max)

print(Max)

Submission status: Accepted

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

v=[int(i) for i in input().split()]
d=[]
ans=[]

for i in range(min(N,K)+1):
    for j in range(i+1):
                
        for k in range(j):
            d.append(v[k])

        for l in range(i-j):
            d.append(v[len(v)-(l+1)])
        
#        print(d)
        for m in range(K-i):
            if len(d)>=1:
                d.sort(reverse=True)
                if d[len(d)-1]<0:
                    d.pop()
#        print(d)
        ans.append(sum(d))
        d=[]

print(max(ans))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
D - equeue
https://atcoder.jp/contests/abc128/tasks/abc128_d

"""
import sys


def dig_lr(n, q, lr='L'):
    # 左(もしくは右)側から最大でn回操作した時の結果の最大値を求める
    res = [0]
    for di in range(1, min(n, len(q))+1): #  diは最大で掘る回数
        bu = n - di             #  埋める方に使用する操作回数
        dig = list(q[:di]) if lr == 'L' else list(q[-di:])
        dig.sort()
        while bu and dig and dig[0] < 0: #  マイナスのアイテムが手元にあればマイナスが大きい方から埋める
            dig.pop(0)
            bu -= 1
        res.append(sum(dig))
    return max(res)


def solve(N, K, V):
    ans = [0]
    limit = sum([v for v in V if v > 0]) #  価値がプラスのアイテムだけ取り出せたときの合計(理論上ベストな結果)
    # K操作回の操作を左右で(左:0 右:K), (左:1 右:K-1), ...,  (左:K 右:0),のように割り振っていき、
    # 左・右からゲットできる値の合計値を計算する
    for left in range(K+1):
        right = K - left
        l_dig = dig_lr(left, V, 'L')
        r_dig = dig_lr(right, V, 'R')
        ans.append(min(limit, l_dig+r_dig))
    return max(ans)


def main(args):
    N, K = map(int, input().split())
    V = [int(v) for v in input().split()]
    ans = solve(N, K, V)
    print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Accepted

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

Submission status: Accepted

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):
        # print(i,j)
        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
        ope = k - (i + j)
        # print(par_seq, par_seq_sum)
        for _ in range(min(ope, len(par_seq))):
            rm = par_seq.pop(0)
            if rm < 0 and sum(par_seq) > ans:
                ans = sum(par_seq)

print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
d=list(map(int,input().split()))
d=d*2
ans=0
for i in range(1,min(k+1,n+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: Accepted

Solution code:
N,K = map(int,input().split())
V = list(map(int,input().split()))
ans = 0
R = min(N,K)
for A in range(R+1):
    for B in range(R-A+1):
        s = V[:A]+V[N-B:]
        #print(s)
        s.sort()
        S = sum(s)
        for k in range(min(K-A-B,len(s))):
            if s[k] < 0:
                S -= s[k]
        ans = max(ans,S)
print(ans)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
V = list(map(int,input().split()))
ans = 0
R = min(N,K)
for A in range(R+1):
    for B in range(R-A+1):
        s = V[:A]+V[N-B:]
        
        s.sort()
        S = sum(s)
        for k in range(min(K-A-B,len(s))):
            
            if s[k] < 0:
                S -= s[k]
        ans = max(ans,S)
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
v = [int(i) for i in input().split()]
res = []
for l in range(min(k+1, n+1)):
    tmp1 = v[:l]
    res.append(sum(tmp1))
    for r in range(min(k, n) - l):
        if r == 0:
            tmp2 = tmp1
        else:
            tmp2 = tmp1 + v[-r:]
        res.append(sum(tmp2))
        for a in range(min(len(tmp2), k-l-r)):
            tmp2.sort()
            tmp3 = tmp2[a+1:]
            res.append(sum(tmp3))
print(max(res))

Submission status: Accepted

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

ans = 0
for a in range(K+1):
    for b in range(a+1):
        if a + b > K:
            break
        for c in range(K+1):
            if a + b + c > K:
                break
            if a + c > N:
                break
            for d in range(c+1):
                if a + b + c + d > K:
                    break
                va = V[:a]
                vc = V[::-1][:c]
                va.sort(reverse = True)
                vc.sort(reverse = True)
                ans = max(ans, sum(va[:a-b]) + sum(vc[:c-d]))
print(ans)

Submission status: Accepted

Solution code:
def solve2():
    N, K = [int(_) for _ in raw_input().split()]
    V = [int(_) for _ in raw_input().split()]
    MAX_GET = min(N, K)
    ans = 0
    for i in range(MAX_GET + 1):
        for j in range(MAX_GET + 1 - i):
            get = V[:i] + V[(N - j):]
            if len(get) == 0:
                continue
            get.sort(reverse = True)
            for k in range(K - i - j):
                if len(get) > 0 and get[-1] < 0:
                    get.pop()
                else:
                    break
            ans = max(ans, sum(get))
    print ans

if __name__ == '__main__':
    solve2()

Submission status: Accepted

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

from bisect import bisect_left

ans = 0
for i in range(1 + min(n, k)):
    for j in range(1 + min(n, k) - i):
        if i == j == 0:
            ans = max(ans, 0)
        else:
            remk = k - i - j
            _v = v[:i] + v[n-j:]
            _v.sort()
            max_i = min(remk, bisect_left(_v, 0))
            ans = max(ans, sum(_v[max_i:]))

print(ans)

Submission status: Accepted

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[::]
  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: Accepted

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, permutations # https://docs.python.org/ja/3/library/itertools.html#itertools.combinations
# https://docs.python.org/ja/3/library/itertools.html#itertools.permutations
from collections import deque, Counter # https://docs.python.org/ja/3/library/collections.html#collections.deque
from heapq import heapify, heappop, heappush, heappushpop, heapreplace # https://docs.python.org/ja/3/library/heapq.html
from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
import heapq
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, 8]
    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(min(k,n)+1):
    if i == 0:
        pass
    else:
        heapq.heappush(hp,vn[i-1])
    hpj = copy.deepcopy(hp)
    for j in range(min(k,n)-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: Accepted

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

result = 0
for i in range(min(N + 1, K + 1)):
    for j in range(min(N - i + 1, K - i + 1)):
        xs = V[:i] + (V[-j:] if j else [])
        t = sum(xs)
        l = K - i - j
        xsm = list(sorted(x for x in xs if x < 0))[:l]
        r = t - sum(xsm)
        # print(i, j, l, xs, t, xsm, r)
        result = max(result, r)

print(result)

Submission status: Accepted

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

from heapq import heappush, heappop
for i in range(1, k+1):
  for j in range(0, i+1):
    minus = []
    l = min(n, j)
    r = min(n-l, i-l)
    cur = 0
    for ll in range(l):
      cur += v[ll]
      if v[ll]<0:
        heappush(minus, v[ll])
    for rr in range(r):
      cur += v[n-rr-1]
      if v[n-rr-1]<0:
        heappush(minus, v[n-rr-1])
    rm = k-l-r
    while rm>0 and len(minus)>0:
      rm -= 1
      cur -= heappop(minus)
    ans = max(ans, cur)
print(ans)

Submission status: Accepted

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

ans = 0
A = 0
while A <= min(K, N):
    B = 0
    lst2 = []
    while B <= min(K, N) - A:
        lst2 = lst[:A]+lst[N-B:]
        lst2.sort()
        count = 0
        for i in range(len(lst2)):
            if lst2[i] <= 0 and i+1 <= K - A - B:
                pass
            else:
                count += lst2[i]
        ans = max(ans, count)
        B += 1
    A += 1

print (ans)

Submission status: Accepted

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

ans = 0
for lr in range(min(n, k)+1):
    for l in range(lr+1):
        r = lr - l
        jewels = v[:l]+v[-r:] if r > 0 else v[:l]
        n_release = k - lr
        ans_cur = 0
        for j in sorted(jewels):
            if j < 0 and n_release > 0:
                n_release -= 1
            else:
                ans_cur += j
        ans = max(ans, ans_cur)
        
print(ans)

Submission status: Accepted

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 not lstop:
            w = V.popleft()
            mny.add(w)
            ans = max(ans, get(cnt-1, mny, lstop, rstop))
            mny.remove(w)
            V.appendleft(w)

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

    if len(mny.red) > 0:
        w = min(mny.red)
        mny.red.remove(w)

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

        mny.red.append(w)    

    return ans

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

Submission status: Accepted

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