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 sys
import numpy as np
input = sys.stdin.readline

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

max_v = 0

for l in range(min(N + 1, K + 1)):
    for r in range(min(N - l + 1, K - l + 1)):
        acts = l + r

        items = V[:l] + V[N - r:]
        minus = sum([item < 0 for item in items])
        if minus <= K - acts:
            total = sum([(item > 0) * item for item in items])
        else:
            items.sort()
            total = sum(items[K - acts:])
        max_v = max(max_v, total)

print(max_v)

Submission status: Accepted

Solution code:
import bisect

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

ans = 0
for a in range(min(N, K)+1):
    for b in range(min(N, K)-a+1):
        score = 0
        D = sorted(V[:a]+V[N-b:])
        score = sum(D[min(K-(a+b), bisect.bisect_left(D, 0)):])
        # print(score)
        ans = max(ans, score)

print(ans)

Submission status: Accepted

Solution code:
#### import ####
import sys
sys.setrecursionlimit(10**7)
import math
from collections import defaultdict

#### 定数 ####
mod = 10**9 + 7

#### 読み込み ####
def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
  read_all = [tuple(map(int, input().split())) for _ in range(N)]
  return map(list,zip(*read_all))

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

N,K = II()
V = III()

ans = -float('inf')
for i in range(min(N+1,K+1)):
  for j in range(min(N-i+1,K-i+1)):
    V2 = V[:i] + V[N-j:]
    V2.sort()
    temp = sum(V2)
    for k in range(min(K-(i+j),len(V2))):
      if V2[k]<0:
        temp -= V2[k]
    if ans < temp:
      ans = temp
print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left


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

    score = 0
    for i in range(n + 1):
        for j in range(n - i + 1):
            if k < i + j:
                continue

            hands = v[:i] + v[n - j:]
            hands = sorted(hands)

            # throw away negative points
            p = min(bisect_left(hands, 0), k - i - j)

            score = max(score, sum(hands[p:]))

    print(score)


main()

Submission status: Accepted

Solution code:
N, K = map(int, input().strip().split())
V = list(map(int, input().strip().split()))
H = []
maxi = 0
for i in range(min(N, K)):
    for o in range(i+2):  # error1
        ts = 0
        hand = []
        for p in range(o):
            hand.append(V[p])
        for p in range(N-(i-o)-1, N):  # error2
            hand.append(V[p])
        for values in hand:
            ts += values
        if ts > maxi:
            maxi = ts
        if len(hand) > 0:
            hand.sort()
            for j in range(K-i-1):  # error3
                if len(hand) > 0:
                    if hand[0] < 0:
                        del hand[0]
                    else:
                        break
        ts = 0
        for k in hand:
            ts += k
        if ts > maxi:
            maxi = ts
print(maxi)

Submission status: Accepted

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

m = min(N, K)
for l in range(m+1):
    for r in range(m+1-l):
        hold = V[:l] + V[N-r:]
        hold.sort()
        for d in range(K+1-l-r):
            ret = max(ret, sum(hold[d:]))

print(ret)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
U = V[::-1]
ret = 0

m = min(N, K)
for l in range(m+1):
    for r in range(m+1-l):
        hold = V[:l] + U[:r]
        hold.sort()
        for d in range(K+1-l-r):
            ret = max(ret, sum(hold[d:]))

print(ret)

Submission status: Accepted

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

r = min(n, k)

#kati(a,b) = 操作Aをa回やって得た宝石の価値 + Bをb回やって得た宝石の価値 - 持ってる宝石の小さい順にs個の価値

def kati(a, b):
  if a == 0 and b == 0:
    return 0
  else:
    ans = 0
    #左から取る
    l = v[:a]
    ans += sum(l)
    #右から取る
    r = v[::-1][:b]
    ans += sum(r)
    have = l + r
  #  print(have)
    #s:捨てれる個数
    s = k - (a + b)
    #持ってる宝石の中で負のやつ
    have = [i for i in have if i < 0]
    #ソート
    have.sort()
    #持ってる宝石の小さい方からsこの合計を引く

    if len(have) <= s:
      ans -= sum(have)
    else:
      ans -= sum(have[:s])
    return ans

# a + b <= r のもとで
# max(kati(a,b))を求める
tmp = []
for a in range(r+1):
  for b in range(r-a+1):
    x = kati(a, b)
 #   print(a,b,x)
    tmp.append(x)

print(max(tmp))

Submission status: Accepted

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

m = min(n, k)
for l in range(m + 1):
    for r in range(m - l + 1):
        s = v[:l] + u[:r]
        s.sort()
        for i in range(k - l - r + 1):
            ans = max(ans, sum(s[i:]))

print(ans)

Submission status: Accepted

Solution code:
from collections import deque

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

R = min(N, K)
ans = 0
for left in range(R+1):
    #print('left', left)
    for right in range(R+1-left):
        if left + right > K:
            continue
        stay = K - left - right
        # print(right, left, stay)
        tmp = inputs[:left] + inputs[::-1][:right]
        tmp.sort()
        total = sum(tmp)
        if stay <= len(tmp):
            tmp = tmp[:stay]
        for item in tmp:
            if item < 0:
                total -= item
            else:
                break
        ans = max(ans, total)

print(ans)

Submission status: Accepted

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

ans=0

getl_sum=0
for lc in range(min(n,k)+1):
    getl_sum += v[lc]
    getr_sum =0
    for rc in range(min(n,k)-lc+1):
        getr_sum += v[-rc-1]
        get = v[:lc] + v[-rc-1:]
        get.sort()
        get_sum = getl_sum + getr_sum
        ans = max(ans,get_sum)
        for bc in range(min(lc+rc,k-lc-rc)):
            get_sum-=get[bc]
            ans = max(ans,get_sum)
print(ans)

Submission status: Accepted

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

N = N + 1 # 選択しなかった場合を追加
res = 0
AB = []
if N < K:
	AB = V
	k = min(K-len(AB), len(AB))
	for idx in range(k):
		if AB[idx] < 0:
			AB[idx] = 0
	res = max(res, sum(AB))
else:
	for a in range(N):
		for b in range(N):
			if a + b <= K:
				AB = V[:a] + revV[:b]
				AB.sort()
				k = min(K-len(AB), len(AB))
				for idx in range(k):
					if AB[idx] < 0:
						AB[idx] = 0
				res = max(res, sum(AB))
print(res)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
c=min(N,K)
p=[0]
for i in range(c+1):
  for j in range(c-i+1):
    a=[0]
    s=0
    for k in range(i):
      s=s+V[k]
      a.append(V[k])
    for l in range(j):
      s=s+V[N-1-l]
      a.append(V[N-1-l])
    for _ in range(K-i-j):
      if min(a) >=0:
        break
      else:
        s=s-min(a)
        a.remove(min(a))
    p.append(s)
print(max(p))

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): # Dequeueからとる宝石の数
    for j in range(i+1):  # 左からとる宝石の数
        Juel = V[:j]+V[N-i+j:]
        Juel.sort()
        sum_v = 0
        for k in range(min(K-i,i)):
            Juel[k] = max(Juel[k],0)
        ans = max(ans,sum(Juel))
print(ans)

Submission status: Accepted

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

def mc(arr):
    count = 0
    for ar in arr:
        if ar<0:
            count += 1
    return count

def ps(arr):
    sum = 0
    for ar in arr:
        if ar > 0 :
            sum += ar
    return sum

maxsumv = 0
for l in range(0,n+1):
    for r in range(0,n+1):
        if l+r > min(k,n):
            break
        else:
            hand = v[0:l] + v[n-r:n]
            hand.sort()
            c = mc(hand)
            for i in range(0,c+1):
                if l+r+i > k:
                    break
                else:
                    sumv = sum(hand[i:len(hand)])
                    maxsumv = max(sumv,maxsumv)
        
print(maxsumv)

Submission status: Accepted

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

def solve():
    N, K = list(map(int, input().split()))
    V = list(map(int, input().split()))
    
    ans = 0
    M = min(N,K)
    for l in range(M+1):
        having = []
        for r in range(M+1):
            if l+r > M: break
            if l+r == 0: continue
            # 左からl, 右からr個の宝石を取り出す
            having = V[:l] + V[::-1][:r]
            having.sort(reverse=True)

            restK = K - (l+r)

            for _ in range(restK):
                if len(having)!=0 and having[-1] < 0:
                    having.pop()
                    continue
                break

            ans = max(ans, sum(having))
    
    print(ans)

if __name__ == "__main__":
    solve()

Submission status: Accepted

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

ans = 0
sz = min(N,K)
for a in range(1+sz):
	for b in range(1+sz-a):
		#print('{} {}'.format(V[:a],V[N-b:]))
		taken = V[:a]+V[N-b:]
		taken.sort()
		for c in range(1+min(K-a-b,a+b)):
			score = sum(taken[c:])
			#print('   ({}) {}'.format(score,taken[c:]))
			ans = max(ans,score)
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def main():
	n, k = map(int, input().strip().split())
	v = list(map(int, input().strip().split()))
	ans = 0
	for a in range(k+1):
		for b in range(k-a+1):
			if a + b > n:
				continue
			t = sorted(v[:a] + v[n-b:])
			for i in range(k-a-b):
				if i < len(t) and t[i] < 0:
					t[i] = 0
			ans = max(ans, sum(t))
	print(ans)
if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#ABC128 D

import sys
import math
import bisect
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
mod = 10**9 + 7

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

ans = -float('inf')
for a in range(min(n,k)+1):
    for b in range(min(n,k)+1 - a):
        x = v[:a] + v[n-b:]
        x.sort()
        preans = sum(x)
        for i in range(k-a-b):
            if i < len(x):
                if x[i] < 0:
                    preans += abs(x[i])
                else:
                    break
            else:
                break
        ans = max(ans,preans)
print(ans)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
li = list(map(int,input().split()))
rim = min(N,K)
mans = 0
for A in range(rim+1):
    for B in range(rim-A+1):
        ansl = sorted(li[:A]+ li[N-B:])
        ans = sum(ansl)
        if ansl ==[]:continue
        #負の宝石を入れ直す
        for i in range(min(K-A-B,len(ansl))):
            if min(ansl) < 0 :
                ans -= min(ansl)
                ansl.remove(min(ansl))
            else:
                break;
        if ans > mans:
            mans = ans
print(mans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
R=min(N,K)
ans=0
for i in range(R+1):
	for j in range(R-i+1):
		if i==0 and j==0:continue
		L=sorted(V[:i]+V[N-j:])
		k=min(K-i-j,len(L)-1)
		for p in range(k):
			if L[p]>=0:
				k=p
				break
		ans=max(ans,sum(L[k:]))
print(ans)

Submission status: Accepted

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

res = 0
for p in range(min(N, K) + 1):
    q = 0
    while p + q <= min(N, K):
        v = []
        cur = 0
        for i in range(p):
            v.append(V[i])
            cur += V[i]
        for i in range(q):
            v.append(V[N-1-i])
            cur += V[N-1-i]
        v.sort()
        for i in range(min(K-p-q, len(v))):
            if v[i] < 0:
                cur -= v[i]
        res = max(res, cur)
        q += 1

print(res)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
jewels = list(map(int, input().split())) + [0]
ans = 0
for get in range(1, min(N, K)+1):
  put = min(get, K-get)
  for left in range(get+1):
    right = get - left
    values = jewels[:left] + jewels[N-right:]
    sum_v = sum(values)
    minus_values = list(filter(lambda x: x<0, values))
    minus_values.sort()
    cnt = 0
    for v in minus_values:
      if cnt < put:
        sum_v -= v
        cnt += 1
      else:
          break
    ans = max(ans, sum_v)
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(n):
    for r in range(n-l+1):
        if l + r > k:
            break #操作は最大k回まで。超えたら次のlへ。
        nv = v[:l] + v[n-r:] #左からl^1個。
        nv.sort()
        for i in range(k-l-r):
            if not nv or nv[0] >= 0:
                break
            del nv[0]
        ans=max(ans,sum(nv))

print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque
from copy import copy

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

max_value = 0

def calc_max_value(V, K, k, l, r):
    store = deque([])
    for i in range(l):
        if len(V)>0:
            store.append(V.popleft())
            continue
        else:
            break
    for i in range(r):
        if len(V)>0:
            store.append(V.pop())
            continue
        else:
            break
    store = deque(sorted(store))
    for i in range(K-l-r):
        if len(store)>0:
            e = store.popleft()
            if e < 0:
                continue
            else:
                store.appendleft(e)
                break
        else:
            break
    max_value = sum(store)
    return max_value

    
for k in range(min(K+1,N+1)):
    for l in range(k+1):
        for r in range(k+1-l):
            max_value = max(max_value, calc_max_value(copy(V), K, k, l, r))

print(max_value)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
#C,D(宝石を手放す)は最後にまとめてよい
#A,Bを行う回数a,b
#取り出せるもののうちできるだけ負かつ
#その絶対値が大きいものを取り出したい
nk=min(n,k)
discard=0
ans=0
for a in range(nk+1):
    for b in range(nk+1):
        if a+b>nk:
            break
        discard=k-(a+b)     #捨てる回数
        dis=v[:a]+v[n-b:]   #両端から取り出すリスト
        minus=[i for i in dis if i<0]  #取り出すもののうち負のもの
        minus.sort()
        ans=max(sum(dis)-sum(minus[:min(discard,len(minus))]),ans)
print(ans)

Submission status: Accepted

Solution code:
import heapq

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

lesser = min(N, K)
ans = 0
for A in range(lesser + 1):
    for B in range(lesser + 1):
        if A + B > lesser:
            continue
        holding = V[:A] + V[N - B:]
        heapq.heapify(holding)
        S = sum(holding)
        CD = K - (A + B)
        for i in range(min(A + B, CD)):
            p = heapq.heappop(holding)
            if p >= 0:
                break
            S -= p
        ans = max(ans, S)
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
v = [int(_) for _ in input().split()]
res = 0
for i in range(n+1):
    for j in range(n+1):
        if i+j > 0 and i+j<=min(n,k):
            l = v[0:i] + v[:-j-1:-1]
            l.sort()
            cnt = 0
            for p in range(len(l)):
                if l[p] >= 0 or cnt >= k-i-j:
                    break
                l[p] = 0
                cnt  += 1
            res = max(res,sum(l))
print(res)

Submission status: Accepted

Solution code:
import sys
from collections import deque, defaultdict
import copy
import bisect
#input=sys.stdin.readline
sys.setrecursionlimit(10 ** 9)


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

max_num = 0
V_left = [0,V[0]]
V_right = [0,V[N - 1]]
V_left_m = [[] for i in range(N + 1)]
V_right_m = [[] for i in range(N + 1)]
for i in range(N - 1):
    V_left.append(V_left[-1] + V[i + 1])
    V_right.append(V_right[-1] + V[N - 2 - i])

for i in range(1, N+1):
    if i == 0:
        minus_l = []
        minus_r = []
    else:
        minus_l = copy.deepcopy(V_left_m[i - 1])
        minus_r = copy.deepcopy(V_right_m[i - 1])
    if V[i - 1] < 0:
        minus_l.append(V[i - 1])
    V_left_m[i] = minus_l
    if V[N  - i] < 0:
        minus_r.append(V[N - i])
    V_right_m[i] = minus_r

for k in range(1, min(N, K) + 1):
    for i in range(0, k + 1):
        point = V_left[i] + V_right[k - i]
        minus = V_left_m[i] + V_right_m[k - i]
        minus = list(minus)
        minus = sorted(minus)
        point -= sum(minus[0:K - k])
        #print(i, k - i, point, minus, minus[0:K - k], K - k)
        if point > max_num:
            max_num = point
           # print(point, i, k-i,minus, minus[0:K-k], K-k)

print(max_num)

Submission status: Accepted

Solution code:
# -*- coding:utf-8 -*-
from collections import deque
"""解説
全探索

左からL個、右からR個宝石を取り、K-(L+R)個の宝石を筒に詰めるとき方針として、

・筒に詰める宝石は絶対値の大きい負の値のもの

あとは全探索
"""

def solve():
    N, K = list(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+1):  # 右から取る個数
            if r < a+b: continue

            t = V[:a] + V[::-1][:b]  # 左からa個、右からb個とった宝石を「持っているリストt」にぶちこむ
            t.sort(reverse=True)

            for _ in range(K-a-b):
                if len(t) > 0 and t[-1] < 0:
                    t.pop()
                    continue
                break
            ans = max(ans, sum(t))

    print(ans)



if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
from collections import deque
res=0
for i in range(min(N+1,K+1)):
    for j in range(min(N+1,K+1)-i):
        cur = list()
        v = deque()
        for f in V:
          v.append(-f)
        ans=0
        for p in range(i):
            cur.append(v.popleft())
        for q in range(j):
            cur.append(v.pop())
        cur=sorted(cur,reverse=True)
        #print(cur)
        for n in range(min(K-i-j,len(cur))):
            if cur[n]>0:
                cur[n]=0
            else:
                break
        res = max(-1*sum(cur),res)
print(res)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import bisect

inf = float('inf')

def solve(N: int, K: int, V: "List[int]"):
    res = -inf
    for k in range(min(K+1, N+1)):
        for left in range(k+1):
            right = k - left
            L = V[:left] + V[N-right:]
            L.sort()
            i = min(bisect.bisect(L, 0), K - k)
            res = max(res, sum(L[i:]))
    print(res)

    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    V = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    solve(N, K, V)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

ans = 0
for a in range(r+1):
    for b in range(r+1):
        if r < a+b:
            continue
        t = V[:a] + V[::-1][:b]
        t.sort(reverse=True)
        for _ in range(K-a-b):
            if len(t) > 0 and t[-1] < 0:
                t.pop()
        if ans < sum(t):
            ans = sum(t)
print(ans)

Submission status: Accepted

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

ans = 0
m = min(n, k)
for i in range(m + 1):
    for j in range(m - i + 1):
        t = v[:i] + v[n - j:]
        t.sort()
        d = tuple(filter(lambda x: x < 0, t))[:k - i - j]
        ans = max(ans, sum(t) - sum(d))
print(ans)

Submission status: Accepted

Solution code:
import sys


def val(l, r, d, Vs):
    jewels = Vs[:l] + list(reversed(Vs))[:r]
    return sum(sorted(jewels)[d:])

def cond(l, r, d, k, N):
    return l + r >= 0 and l + r <= min([k, N]) and d <= l + r


def main():
    input = sys.stdin.readline
    N, K = map(int, input().split())
    Vs = list(map(int, input().split()))

    ans = 0
    for k in range(K+1):
        for l in range(min([k+1, N+1])):
            for r in range(min([k+1, N+1])):
                d = k - l - r
                if cond(l, r, d, k, N):
                    ans = max(ans, val(l, r, d, Vs))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for lk in range(min(K, N)+1):
    for rk in range(min(K, N)+1-lk):
        k = K - lk - rk
        v = V[:lk] + V[N-rk:]
        v.sort()
        ans = max(sum(v[k:]) + sum([x for x in v[:k] if x > 0]), ans)
if K >= 2 * N:
    ans = sum([v for v in V if v >= 0])
print(ans)

Submission status: Accepted

Solution code:
from sys import stdin
import numpy as np

N, K = map(int,stdin.readline().rstrip().split())
VList = list(map(int,stdin.readline().rstrip().split()))
VList=np.array(VList)

maxNum=0
tryNum = min(N,K)
for i in range(tryNum+1):
  for j in range(tryNum+1-i):
    getList=VList[0:i]
    getList=np.append(getList,VList[N-j:N])
    getList.sort()
    throwNum=min(K-(i+j), len(getList))
    counter=0
    for k in range(throwNum):
      if getList[k] < 0:
        counter+=1
    getList=getList[counter:len(getList)]
    maxNum=max(maxNum, sum(getList))
print(maxNum)

Submission status: Accepted

Solution code:
import numpy as np
n,k = map(int,input().split())

arr = list(map(int,input().split()))
s = [0 for i in range(n)]
temp = 0
ans = 0

for i in range(1,k+1):
    upper = min(n,i)
    for j in range(upper+1):
        v = 0
        a = []
        for l in range(j):
            v += arr[l]
            a.append(arr[l])
        for l in range(1,upper+1-j):
            v+= arr[-l]
            a.append(arr[-l])
        a.sort()
        # print(a,v)
        up = min(k-upper,i)
        for l in range(up):
            if a[l] < 0:
                v -= a[l]
            else:
                break
        if v > ans:
            ans = v

print(ans)

Submission status: Accepted

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

def main():
	n, k = map(int, input().strip().split())
	v = deque(map(int, input().strip().split()))
	ans = 0
	for i in range(k+1):
		for j in range(k - i + 1):
			now = 0
			s = []
			if i + j > n:
				continue
			md = k - i - j
			for t in range(i):
				s.append(v[t])
				now += v[t]
			for t in range(j):
				s.append(v[n-1-t])
				now += v[n-1-t]
			s.sort()
			# for t in range(min(md, i+j)):
			# 	# print("t:{}, len:{}".format(t, len(s)))
			# 	if s[t] >= 0:
			# 		break
			# 	else:
			# 		s[t] = 0
			for t in range(md):
				if t >= len(s):
					break
				if s[t] >= 0:
					break
				now -= s[t]
			ans = max(now, ans)

	print(ans)


if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
# from collections import deque
n,k=map(int,input().split())
a=list(map(int,input().split()))
# v=deque()
# for i in range(n):
#     v.append(a[i])
# print(v)

ans=0
for i in range(1,k+1):
    if i<=n:
        for j in range(i+1):
            tmp=[]
            # print("{0} {1}".format(i,j))
            for l in range(j):
                if l<n:
                    tmp.append(a[l])
            for r in range(i-j):
                if n-1-r>=0:
                    tmp.append(a[-1-r])
            # print(tmp)
            tmp.sort(reverse=True)
            # print(tmp)
            for m in range(k-i):
                if len(tmp)>0:
                    if tmp[-1]<0:
                        tmp.pop()
            ans=max(ans,sum(tmp))

print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
V_=list(reversed(V))
ans=0
for k in range(1,K+1):
    k_=min(k,N)
    for kk in range(k_+1):
        sum=0
        l=[]
        for i in range(kk):
            sum+=V[i]
            l.append(V[i])
        for i in range(k_-kk):
            sum+=V_[i]
            l.append(V_[i])
        l.sort()
        for j in range(min(k_,K-k_)):
            if l[j]>=0:
                break
            sum-=l[j]
        ans=max(ans,sum)
print(ans)

Submission status: Accepted

Solution code:
import itertools as it

n, k = map(int, input().split())
vs = [int(s) for s in input().split()]
vs_acc = [0] + list(it.accumulate(vs))
vs_total = vs_acc[-1]

ans = 0
for left in range(min(n, k) + 1):
    for right in range(min(n, k) - left + 1):
        cnt = k - (left + right)
        remaining = vs_acc[n - right] - vs_acc[left]
        subsum = vs_total - remaining

        rest = sorted(vs[:left] + vs[n - right :])[:cnt]
        for x in rest:
            if x < 0:
                subsum -= x
            else:
                break
        ans = max(ans, subsum)

print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque  # 双方向キュー
from collections import defaultdict  # 初期化済み辞書
from heapq import heapify, heappush, heappop, heappushpop  # プライオリティキュー
from bisect import bisect_left, bisect_right  # 二分探索
#import numpy as np  # 1.8.2
#import scipy  # 0.13.3
#sys.setrecursionlimit(int(1e+6))
s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in ss]
ss2nnn = lambda ss: [s2nn(s) for s in ss]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline().rstrip() for _ in range(n)]
ii2sss = lambda n: [list(sys.stdin.readline().rstrip()) for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))
MOD = int(1e+9) + 7

def main():
    N, K = i2nn()
    V = i2nn()
    n = 0
    for i in range(min(N+1, K+1)):
        for j in range(min(N+1-i, K+1-i)):
            k = K - i - j
            w = V[0:i] + V[N-j:N]
            w.sort()
            t = 0
            for u in w:
                if u < 0 and k > 0:
                    k -= 1
                    continue
                t += u
            if n < t:
                n = t
    print(n)

main()

Submission status: Accepted

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]

def main():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    lenV = len(V)

    res = 0
    for k in range(1, K+1):
        if lenV < k: break
        for rk in range(k+1):
            pick_list = V[:k-rk]
            if 0 < rk:
                pick_list.extend(V[-rk:])
            pick_list.sort()

            # remove negative number in pick_list
            not_neg_start_index = 0
            for i, num in enumerate(pick_list):
                if num < 0: continue
                else:
                    not_neg_start_index = i
                    break
            pos_sum = sum(pick_list[i:])
            neg_list = pick_list[:i]
            len_neg_list = len(neg_list)
            if K-k < len_neg_list:
                res = max(res, sum(neg_list[K-k:])+pos_sum)
            else:
                res = max(res, pos_sum)
    print(res)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]

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

res = 0
for k in range(1, K+1):
    if lenV < k: break
    for rk in range(k+1):
        pick_list = V[:k-rk]
        if 0 < rk:
            pick_list.extend(V[-rk:])
        pick_list.sort()

        # remove negative number in pick_list
        not_neg_start_index = 0
        for i, num in enumerate(pick_list):
            if num < 0: continue
            else:
                not_neg_start_index = i
                break
        pos_sum = sum(pick_list[i:])
        neg_list = pick_list[:i]
        len_neg_list = len(neg_list)
        if K-k < len_neg_list:
            res = max(res, sum(neg_list[K-k:])+pos_sum)
        else:
            res = max(res, pos_sum)

print(res)

Submission status: Accepted

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

nk = min(N, K)

ans = -1
for a in range(nk+1):
    for b in range(nk+1-a):
        have = v[:a] + v[N-b:]
        have = sorted(have)
        i = 0
        while i < K - a - b and i < a + b:
            if have[i] < 0:
                have[i] = 0
            else:
                break
            i += 1
        ans = max(ans, sum(have))

print(ans)