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:
N,K=list(map(int,input().split()))
V=list(map(int,input().split()))
max_score=0
for k in range(min(N,K)+1):#合計取る個数
    for k_l in range(k+1):# 左から取る個数
        left=V[:k_l]
        k_r = k-k_l
        right=V[-k_r:]if k_r>0 else []
        sterable=sorted(left+right)[:K-k]
        stesum=0
        for ss in sterable:
            if ss<0:
                stesum+=ss
            else:break
        score = sum(left)+sum(right) - stesum
        max_score=max(score,max_score)
print(max_score)

Submission status: Accepted

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

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

Submission status: Accepted

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

max_price = 0
for pick in range(1, min(K, N) + 1):
    for left_pick_num in range(pick + 1):
        right_pick_num = max(pick - left_pick_num, 0)
        if not left_pick_num and not right_pick_num: continue
#        print("Pick {} from left, {} from right".format(left_pick_num, right_pick_num))
        picked = gems[:left_pick_num]
        if right_pick_num: picked += gems[-right_pick_num:]
#        print("Pick {} gems".format(pick))
#        print("The gems picked: {}".format(picked))
        picked.sort()
        num_throw = min(pick, K - pick)
        j = 0
        while j < num_throw and picked[j] < 0:
            j += 1
#        print("The gems picked after throwing: {}".format(picked[j:]))
        max_price = max(max_price, sum(picked[j:]))
print(max_price)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
V = list(map(int,input().split()))
res = 0
for i in range(1,min(N+1,K+1)): #獲得の回数
  for j in range(i+1):#Aの回数
    have = []
    trash_value = 0
    a = j
    b = i - j
    have.extend(V[:a])
    if not b ==0:
      have.extend(V[((-1)*b):])
    have.sort()
    trash = K - i #捨てる回数
    for p in range(min(trash,len(have))):
      if have[p] < 0:
        trash_value += have[p]
      else:
        break
    if res < (sum(have)-trash_value):
      res = (sum(have)-trash_value)
print(res)

Submission status: Accepted

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

for a in range(lim+1):
    for b in range(lim-a+1):
        hand = sorted(v[:a]+v[n-b:])
        hs = sum(hand)
        for i in range(min(k-a-b, a+b)):
            test = hand[i]
            if test < 0:
                hs -= test
        ans.append(hs)
print(max(ans))

Submission status: Accepted

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

# -*- coding: utf-8 -*-


from sys import stdin
import itertools
import time


############################################

import numpy as np
# read data for n sequences.
temp = stdin.readline().split()
N = int(temp[0])
K = int(temp[1])

data = []
write = stdin.readline().split()
for a in write:
    data.append(int(a))

steps = min(N, K)

# A.. 左から取る数
# B.. 右から取る数

An = range(K+1)

max = 0

for A in An:
    for B in range(steps-A+1):       
        small = K - A - B
#        print("A:",A,"B:",B,"small:",small)
        left = data[0:A]
        right = []
        if not B==0:
            right = data[-B:]
        left.extend(right)
        left = sorted(left)
#        print(left)
        # remove stuff
        for k in range(small):
#            print(k)
            try:
                if left[k] <= 0:
                    left[k] = 0
            except:
                continue
        
        add = sum(left)
#        print(add)
        if max < add:
            max = add
print(max)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
Vs = list(map(int, input().split()))
max_v = 0
R = min(N, K)
for r in range(R+1):
  for a in range(r+1):
    b = r - a
    inh = sorted(Vs[:a] + Vs[N-b:])
    for d in range(min(r, K-r)+1):
      max_v = max(max_v, sum(inh[d:]))

print(max_v)

Submission status: Accepted

Solution code:
import sys
from collections import deque
import copy
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: Accepted

Solution code:
# -*- coding: utf-8 -*-
n,k = map(int, input().split())
v = [int(z) for z in input().split()]
ans = []
m = min(n,k)

for a in range(0,min(n,k)+1):
    for b in range(0,min(n,k)-a+1):
        vm = []
        cd = k-a-b
        vm.extend(v[0:a])
        vm.extend(v[n-b:n])
        vm.sort()
        for i in range(0,min(cd,len(vm))):
            if vm[i] < 0:
                vm[i] = 0
        ans.append(sum(vm))

print(max(ans))

Submission status: Accepted

Solution code:
N,K = [int(x) for x in input().split()]
V = [int(x) for x in input().split()]
#%%
dp = [[0 for _ in range(N+1)]for _ in range(N+1)]
ans = -10**10
for i in range(N+1):
    for j in range(N+1):
        if(i+j>min(K,N)): continue
        li = []
        if(j!=0):
            li = V[:i]+V[-j:]
        else:
            li = V[:i]
        cnt = 0
        li.sort()
        for x in li:
            if(x<0):
                cnt+=1
            else:
                break
        if(min(cnt,K-(i+j))<0):
            print('aaa')
        dp[i][j] = sum(li[min(cnt,K-(i+j)):])
        ans = max(ans,sum(li[min(cnt,K-(i+j)):]))

print(ans)

Submission status: Accepted

Solution code:
import sys

import numpy as np

sys.setrecursionlimit(10000)
INF = float('inf')
N, K = list(map(int, input().split()))
V = np.array(list(map(int, input().split())))
Vminus = np.minimum(V, 0)

ans = 0
for take in range(min(N, K) + 1):
    discards = min(K - take, take)
    for t in range(take + 1):
        v = sum(V[:take - t]) + sum(V[N - t:])
        minuses = list(sorted(np.concatenate([Vminus[:take - t], Vminus[N - t:]])))
        ans = max(ans, v - sum(minuses[:discards]))
print(ans)

Submission status: Accepted

Solution code:
import sys
def LI(): return [int(x) for x in sys.stdin.readline().split()]

def main():
    デックの長さ, 操作可能回数 = LI()
    デック = LI()

    最大値 = 0
    for 取る数 in range(min(操作可能回数+1, デックの長さ+1)):
        捨てることができる数 = 操作可能回数 - 取る数
        for 左から取る数 in range(取る数+1):
            右から取る数 = 取る数 - 左から取る数
            取ったリスト = デック[:左から取る数] + デック[デックの長さ-右から取る数:]
            取ったリスト = sorted(取ったリスト)
            for _ in range(捨てることができる数):
                if 取ったリスト and 取ったリスト[0] < 0:
                    取ったリスト.pop(0)
                else:
                    break
            最大値 = max(最大値, sum(取ったリスト))

    print(最大値)

main()

Submission status: Accepted

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

# 操作Aをa回、操作Bをb回、操作Cをc回実行したときの宝石の価値の合計値U(a, b, c)を求める。
# 各 a, b, c について U(a, b, c) の最大値を解とする。
ans = max(
    sum(sorted(V[:a] + V[(N - b):])[c:])
    for a in range(min(N, K) + 1)
    for b in range(min(N, K) - a + 1)
    for c in range(min(K - a - b, a + b) + 1)
)

# 出力
print(ans)

Submission status: Accepted

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

ans = 0
for i in range(min(n, k) + 1):
    for j in range(min(n, k) + 1 - i):
        if i == 0 and j == 0:
            continue
        if j == 0:
            vv = v[:i]
        else:
            vv = v[:i] + v[-j:]
        num = sum(vv)
        vv.sort()
        for l in range(min(len(vv), k - i - j)):
            if vv[l] < 0:
                num -= vv[l]
            else:
                break
        ans = max(ans, num)
print(ans)

Submission status: Accepted

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)
            heapq.heapify(motimono)
            for i in range(K-j): # 戻す個数
                if len(motimono)>0:
                    heapq.heappop(motimono)
                ans.append(sum(motimono))
    print(max(ans))

Submission status: Accepted

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

ans = -pow(10, 9)
for left in range(0, K + 1):
  for right in range(0, K - left + 1):
    if left + right < N:
      all_get = V[:left] + V[::-1][:right]
    else:
      all_get = V[:]
    all_get.sort(reverse=True)
    num = 0
    while True:
      if num >= K - (left + right) or len(all_get) == 0:
        break
      if all_get[-1] >= 0:
        break
      all_get.pop(-1)
      num += 1
    now = sum(all_get)
    ans = max(ans, now)
print(ans)

Submission status: Accepted

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

# N < Kの場合があることに注意


INT_MIN = -1 * (10**10)

ans = INT_MIN

NK = min(N, K)
for left in range(0,NK+1):
    for right in range(0, NK+1-left):
        #print("========")
        #print(left, right)
        #print(V[:left], V[left:N-right], V[N-right:])
        
        rest_ope = K-left-right
        #print(rest_ope)
        my_v = V[:left]+V[N-right:]
        sum_v = 0
        for i, x in enumerate(sorted(my_v)):
            if x < 0 and i < rest_ope:
                continue
            else:
                sum_v += x
        #print(sum_v)
        ans = max(ans, sum_v)
        
print(ans)

Submission status: Accepted

Solution code:
import sys, math, collections, heapq, itertools
F = sys.stdin
def single_input(): return F.readline().strip("\n")
def line_input(): return F.readline().strip("\n").split()
def gcd(a, b):
    a, b = max(a, b), min(a, b)
    while a % b > 0: a, b = b, a % b
    return b
  
def solve():
    N, K = map(int, line_input())
    V = [int(v) for v in line_input()]
    maxpoint = 0
    for i in range(N + 1):
        for j in range(N - i + 1):
            if i + j <= min(N, K):
                trash = []
                heapq.heapify(trash)
                point = sum(V[:i])
                for k in range(j):
                    point += V[-1 - k]
                    heapq.heappush(trash, V[-1-k])
                for a in range(i):
                    heapq.heappush(trash, V[a])
                count = 0
                while trash and count < K - (i + j):
                    bye = heapq.heappop(trash)
                    count += 1
                    if bye > 0: break
                    else: 
                        point -= bye
                maxpoint = max(maxpoint, point)
    print(maxpoint)
    return 0
  
if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
from collections import deque
N,K = map(int, raw_input().split())
V = map(int, raw_input().split())
q = deque([])
nl = []
for i in range(min(K+1,N+1)):
	for j in range(i+1):
		q.append(V[:j]+V[N-i+j:])
	while q:
		q2 = q.popleft()
		q2.sort()
		qlen = len(q2)
		np = sum(q2)
		for j in range(min(qlen,K-i)):
			if(q2[j] < 0):
				np -=q2[j]
		nl.append(np)
print(max(nl))

Submission status: Accepted

Solution code:
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

N,K = map(int,input().split())
V = [int(i) for i in input().split()]
#
# if N == 1:
#     print(max(0,V[0]))
#     exit()

ans = 0
for i in range(K): # 戻す数
    for j in range(K-i+1):
        if j <= N-(K-i-j):
            ans_list = V[:j]+V[N-(K-i-j):]
            ans_list.sort()
            tmp = sum(ans_list)
            for k in range(min(len(ans_list),i)):
                if ans_list[k] < 0:
                    tmp -= ans_list[k]
            ans = max(ans,tmp)
        else:
            pass

print(max(ans,0))

Submission status: Accepted

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

vmax = 0
for l in range(0, K + 1):
	for r in range(0, K - l + 1):
		if N < l + r:
			break
		tv = V[:l] + V[N - r:]
		#print(tv)
		tv.sort()
		for n in range(min(len(tv), K - (l + r))):
			if tv[n] < 0:
				tv[n] = 0
		vmax = max(vmax, sum(tv))

print(vmax)

Submission status: Accepted

Solution code:

import sys
input = sys.stdin.readline
inf = float('inf')
mod = 10**9+7


def INT_(n): return int(n)-1


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


def MF(): return map(float, input().split())


def MI_(): return map(INT_, input().split())


def LI(): return list(MI())


def LI_(): return [int(x) - 1 for x in input().split()]


def LF(): return list(MF())


def LIN(n: int): return [input() for _ in range(n)]


def LLIN(n: int): return [LI() for _ in range(n)]


def LLIN_(n: int): return [LI_() for _ in range(n)]


def LLI(): return [list(map(int, l.split())) for l in input()]


def I(): return int(input())


def F(): return float(input())


def ST(): return input().replace('\n', '')


def main():
    from itertools import accumulate
    import heapq
    N, K = MI()
    V = LI()
    left_cum = [0]+list(accumulate(V))
    right_cum = [0] + list(accumulate(V[::-1]))

    minus_left = [[0]*N]
    minus_right = [[0]*N]
    now_minuses = [0]*N

    for i, v in enumerate(V):
        heapq.heappush(now_minuses, v)
        minus_left.append(list(now_minuses))

    now_minuses = [0]*N
    for i in range(N)[::-1]:
        heapq.heappush(now_minuses, V[i])
        minus_right.append(list(now_minuses))

    ans = 0
    for left in range(N+1):
        for right in range(N+1):
            if left + right > N or left + right > K:
                break
            ans_ = left_cum[left] + right_cum[right]
            l, r = list(minus_left[left]), list(minus_right[right])
            for i in range(K - right - left):
                if l[0] > r[0]:
                    pop_item = heapq.heappop(r)
                else:
                    pop_item = heapq.heappop(l)
                if pop_item >= 0:
                    break
                else:
                    ans_ -= pop_item

            ans = max(ans, ans_)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

import sys
input = sys.stdin.readline
inf = float('inf')
mod = 10**9+7


def INT_(n): return int(n)-1


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


def MF(): return map(float, input().split())


def MI_(): return map(INT_, input().split())


def LI(): return list(MI())


def LI_(): return [int(x) - 1 for x in input().split()]


def LF(): return list(MF())


def LIN(n: int): return [input() for _ in range(n)]


def LLIN(n: int): return [LI() for _ in range(n)]


def LLIN_(n: int): return [LI_() for _ in range(n)]


def LLI(): return [list(map(int, l.split())) for l in input()]


def I(): return int(input())


def F(): return float(input())


def ST(): return input().replace('\n', '')


def main():
    from itertools import accumulate
    import heapq
    N, K = MI()
    V = LI()
    left_cum = [0]+list(accumulate(V))
    right_cum = [0] + list(accumulate(V[::-1]))

    minus_left = [[0]*N]
    minus_right = [[0]*N]
    now_minuses = [0]*N

    for i, v in enumerate(V):
        heapq.heappush(now_minuses, v)
        minus_left.append(list(now_minuses))

    now_minuses = [0]*N
    for i in range(N)[::-1]:
        heapq.heappush(now_minuses, V[i])
        minus_right.append(list(now_minuses))

    # print(*minus_left[1])
    # print(*minus_right)

    ans = 0
    for left in range(N+1):
        for right in range(N+1):
            if left + right > N or left + right > K:
                break
            ans_ = left_cum[left] + right_cum[right]
            l, r = list(minus_left[left]), list(minus_right[right])
            for i in range(K - right - left):
                if l[0] > r[0]:
                    pop_item = heapq.heappop(r)
                else:
                    pop_item = heapq.heappop(l)
                if pop_item >= 0:
                    break
                else:
                    """print(left, right, left_cum[left],
                          right_cum[right], K, ans_, pop_item)"""
                    ans_ -= pop_item
            #print(left, right, left_cum[left], right_cum[right], K, ans_)

            ans = max(ans, ans_)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
R = lambda: map(int, input().split())
n, k = R()
v = list(R())
ans = 0
for i in range(1, min(n, k) + 1):
    for j in range(i):
        t = v[:i - j] + v[n - j:]
        ans = max(ans, sum(t) - sum(sorted(x for x in t if x < 0)[: k - i]))
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:



def main():

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

    ans = 0

    for left in range(min(num_houseki, num_sousa) + 1):
        for righ in range(min(num_sousa- left, num_houseki - left) + 1):
            data_left = data[:left]
            data_righ = data[num_houseki - righ:]
            data_now = data_left + data_righ
            data_now.sort()
            nokori = num_sousa - len(data_now)

            while nokori > 0:
                if len(data_now) == 0:
                    break
                if data_now[0] < 0:
                    data_now.pop(0)
                    nokori -= 1
                else:
                    break

            kari = sum(data_now)
            if kari > ans:
                ans = kari

    print(ans)





if __name__ == '__main__':
    main()

Submission status: Accepted

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

ans = 0

P = min(N,K)

for a in range(1,P+1) :
    for i in range(a+1) :
        cnt = 0
        calc = 0
        GET = V[:i] + V[N-(a-i):]
        GET = sorted(GET)
        
        for g in GET :
            if (g < 0) and (cnt < K-a) :
                cnt += 1
            else :
                calc += g
        
        ans = max(ans, calc)
print(ans)

Submission status: Accepted

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

R = min(N, K)
max_sum = 0
for A in range(R + 1):
        for B in range(R - A + 1):
                drop_max = min(K - (A + B), (A + B))
                if B == 0:
                        L = D[:A]
                else:
                        L = D[:A] + D[-B:]
                L.sort()
                drop_num = 0
                for i in range(A + B):
                        if drop_num < drop_max and L[i] < 0:
                                L[i] = 0
                                drop_num += 1
                        else:
                                break

                max_sum = max(max_sum, sum(L))

                

print(max_sum)

Submission status: Accepted

Solution code:
#https://atcoder.jp/contests/abc128
# -*- coding: utf-8 -*-

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

ans = 0
for left in range(k+1):
    for right in range(k-left+1):
        if left+right > n : continue
        for trash in range (k-left-right+1):
            x = sorted(v[0:left]+v[::-1][0:right])[trash:]
            ans = max(ans,sum(x))

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
Vs = list(map(int, input().split()))
lV = [0]*(N+1)
rV = [0]*(N+1)
lm = [[] for _ in range(N+1)]
rm = [[] for _ in range(N+1)]
for i in range(1, N+1):
    lV[i] += Vs[i-1]+lV[i-1]
    rV[i] += Vs[-i] + rV[i-1]
    if Vs[i-1] < 0:
        for j in range(i, N+1):
            lm[j].append(Vs[i-1])
    if Vs[-i] < 0:
        for j in range(i, N+1):
            rm[j].append(Vs[-i])
ans = 0
for i in range(min(N+1, K+1)):#左からi個とる
    for j in range(min(N+1-i, K+1-i)):
        for k in range(max(1, K+1-i-j)):#k個負の数を捨てる
            SUM = lV[i]+rV[j]
            minus = lm[i]+rm[j]
            minus.sort()
            SUM -= sum(minus[:k])
            if ans < SUM:
                ans = SUM
print(ans)

Submission status: Accepted

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

maxValue = 0

for i in range(min(N,K)+1):
    for j in range(min(N,K)-i+1):
        left = D[:i]
        right = D[N-j:]
        merge = (left + right + [0])
        merge.sort()

        index = 0

        for k in range(K-i-j):
            if (merge[index] < 0):
                index += 1
            else:
                break

        val = sum(merge[index:])
        if(maxValue < val):
            maxValue = val

print(maxValue)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for L in range(min(N, K+1)):
    for R in range(min(N-L, K-L)+1):
        js = V[:L] + V[-R:] if R > 0 else V[:L]
        t = K - L - R
        s = 0
        for i in sorted(js):
            if i < 0 and t > 0:
                s += -i
                t -= 1
        ans = max(ans, sum(js) + s)
print(ans)

Submission status: Accepted

Solution code:
#https://atcoder.jp/contests/abc128
# -*- coding: utf-8 -*-

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

ans = []
for left in range(k+1):
    for right in range(k-left+1):
        if left+right > n : continue
        for trash in range (k-left-right+1):
            x = sorted(v[0:left]+v[::-1][0:right])[trash:]
            ans.append(sum(x))

print(max(ans))

Submission status: Accepted

Solution code:
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([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: Accepted

Solution code:
from itertools import chain, 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(chain(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: Accepted

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

Solution code:
from itertools import chain, 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[m] for m in chain(range(i - j), range(n - j, n))) -
          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: Accepted

Solution code:
from itertools import chain
 
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)
r = 0
for i in range(1, min(n, k) + 1):
    for j in range(i):
        r1, r2 = i - j, n - j
        s = sum(v[m] for m in chain(range(r1), range(r2, n)))
        j = i
        for x, m in a:
            if j == k:
                break
            if m < r1 or m >= r2:
                s -= x
                j += 1
        r = max(r, s)
print(r)

Submission status: Accepted

Solution code:
from itertools import chain
 
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)
r = 0
for i in range(1, min(n, k) + 1):
    for j in range(i):
        r1, r2 = range(i - j), range(n - j, n)
        s = sum(v[m] for m in chain(r1, r2))
        j = i
        for x, m in a:
            if j == k:
                break
            if m in r1 or m in r2:
                s -= x
                j += 1
        r = max(r, s)
print(r)

Submission status: Accepted

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

ans = 0

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+1):
      ans = max(ans, sum(st[:i+j-suteru]))
    
print(ans)

Submission status: Accepted

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+1):
      ans = max(ans, sum(st[:i+j-suteru]))
    
print(ans)

Submission status: Accepted

Solution code:
from numpy import*
n,k,*v=int64(open(0).read().split())
m=0
for i in range(n):
 for j in range(min(k,n)-i+1):t=sort(v[:i]+v[:~j:-1]);m=max(m,sum(t)-sum(t[t<0][:k-i-j]))
print(m)

Submission status: Accepted

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

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

maxv = 0
for l in range(min(K, N) + 1):
    for r in range(min(K, N) - l + 1):
        gets = V[:l + 1] + V[-1 - r:]
        d = K - l - r
        #print("il={},ir={},d={},gets={}".format(il,ir,d,gets))
        for i in range(d):
            if len(gets) <= 0:
                break
            v = min(gets)
            if v >= 0:
                break
            #print("remove={}".format(v))
            gets.remove(v)
        maxv = max(maxv, sum(gets))
        #print("sum(gets)={}".format(sum(gets)))

print(maxv)

Submission status: Accepted

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

maxv = 0
for l in range(min(K, N) + 1):
    for r in range(min(K, N) - l + 1):
        gets = V[:l + 1] + V[-1 - r:]
        gets.sort()
        d = K - l - r
        #print("il={},ir={},d={},gets={}".format(il,ir,d,gets))
        for i in range(d):
            if len(gets) <= 0:
                break
            v = min(gets)
            if v >= 0:
                break
            #print("remove={}".format(v))
            gets.remove(v)
        maxv = max(maxv, sum(gets))
        #print("sum(gets)={}".format(sum(gets)))

print(maxv)

Submission status: Accepted

Solution code:
from numpy import*
n,k,*v=map(int,open(0).read().split())
m=0
for i in range(n):
 for j in range(min(k,n)-i+1):t=sort(v[:i]+v[:~j:-1]);m=max(m,sum(t)-sum(t[t<0][:k-i-j]))
print(m)

Submission status: Accepted

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

ans = 0

for left in range(0, K + 1) :
    for right in range(0, K - left + 1) :
        if left + right > N :
            break

        cd = K - left - right

        res = 0
        minus = []

        for vi in V[:left] :
            if vi < 0 :
                minus.append(vi)
            res += vi

        for vi in V[-1:-1-right:-1] :
            if vi < 0 :
                minus.append(vi)
            res += vi

        if len(minus) > cd :
            minus.sort()
            res -= sum(minus[:cd])
        else :
            res -= sum(minus)

        ans = max(ans, res)

print(ans)