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
input = sys.stdin.readline
ri = lambda: int(input())
rl = lambda: list(map(int,input().split()))
rr = lambda N: [ri() for _ in range(N)]
YN = lambda b: print('YES') if b else print('NO')
yn = lambda b: print('Yes') if b else print('No')
OE = lambda x: print('Odd') if x%2 else print('Even')
INF = 10**18
MOD = 10**9+7

N,K=rl()
V=rl()
mV = [0]*(N)
mc = 0
for i in range(N):
    v = V[i]
    if v < 0:
        mV[i] = v
        mc += 1
rV = V[::-1]
rmV = mV[::-1]

if K >= (N+mc):
    print(sum(V)-sum(mV))
else:
    ans = 0
    for lc in range(K+1):
        rc = K - lc
        rr = 0
        l_ind = 0
        for ind in range(lc+1):
            if ind > N: break
            rm = lc - ind
            rr_ = sum(V[:ind])-sum(sorted(mV[:ind])[:rm])
            if rr < rr_:
                rr = rr_
                l_ind = ind
        rl = 0
        for ind in range(rc+1):
            if ind + l_ind > N: break
            rm = rc - ind
            rl = max(rl,sum(rV[:ind])-sum(sorted(rmV[:ind])[:rm]))
        ans = max(ans, rr+rl)
    print(ans)

Submission status: Accepted

Solution code:
import bisect
 
N, K = map(int, input().split())
V = [int(_) for _ in input().split()]
ans = 0
M = min(N, K)
 
for i in range(M+1):
    for j in range(M-i+1):
        tmplist = sorted(V[:i] + V[-1:-1-j:-1])
        minusindex = bisect.bisect_left(tmplist, 0)
        if minusindex == 0:
            tmpans = sum(tmplist)
        else:
            tmpans = sum(tmplist) - sum(tmplist[:min(minusindex, K-(i+j))])
            
        if tmpans > ans:
            ans = tmpans
 
print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
V=[int(a) for a in input().split()]
able=min(N,K)
ans=0
 
for a in range(able+1):
    for b in range(able+1-a):
        if b==0:
            have=V[:a]
        else:
            have=V[:a]+V[-b:]
        have.sort()

        for i in range(min(a+b,K-a-b)+1):
            val=sum(have[i:])
            if ans<val:
                ans=val
 
print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
V=[int(a) for a in input().split()]
able=min(N,K)
ans=0
 
for a in range(able+1):
    for b in range(able+1-a):
        if b==0:
            have=V[:a]
        else:
            have=V[:a]+V[-b:]
        have.sort()

        for i in range(min(a+b,K-a-b)+1):
            val=sum(have[i:])
            if ans<val:
                ans=val
 
print(ans)

Submission status: Accepted

Solution code:
#入力部
N, K = map(int, input().split())
V = list(map(int, input().split()))
V2 = list(reversed(V))  #反転したリスト
ans = 0 #最終出力


for i in range(K+1):
  for j in range(K+1-i):
    mylist = []
    #指定回数以上はbreak
    if i+j > N:
      break
    mylist = (V[:i])
    mylist.extend(V2[:j])
    #加算のみでの最大値を求める
    mysum = sum(mylist)
    #減算した方が良い場合を求める
    mylist.sort()
    for m in range(min(K - i - j, i+j)): #規定回数と実際に加算されている数を考慮
      #0以上の数は減算非対象
      if mylist[m] >= 0:
        break
      mysum -= mylist[m]
    #減算しない場合かする場合かの最大値が解
    ans = max(mysum, ans)
print(ans)

Submission status: Accepted

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

for l in range(K + 1):
	for r in range(K - l + 1):
		inHand = []
		if l + r > N:  # Nを超えてしまうありえない場合を処理
			break
		# inHandに左からl個、右からr個の要素を追加
		inHand = V[: l]
		inHand.extend(V[N - r:])
		tmp = sum(inHand)  # 現時点でのinHandの和をtmpとして負の要素をtmpから引いていく
		# inHand中の負の要素を消せるだけ消す
		inHand.sort()
		for i in range(min(K - l - r, l + r)):
			if inHand[i] >= 0:
				break
			tmp -= inHand[i]
		ans = max(ans, tmp)

print(ans)

Submission status: Accepted

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

ans = 0
for i in range(min(N, K)+1):
    for j in range(min(N, K)-i+1):
        if j==0:
            temp = List[:i]
        else:
            temp = List[:i]+List[-j:]
        for k in range(min(i+j, K-(i+j))+1):
            ret = sum(sorted(temp)[k:])
            if ret>ans:
                ans = ret
                
print(ans)

Submission status: Accepted

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

ans = [0]
for i in range(min(N, K)+1):
    for j in range(min(N, K)-i+1):
        if j==0:
            temp = List[:i]
        else:
            temp = List[:i]+List[-j:]
        for k in range(min(i+j, K-(i+j))+1):
            ans.append(sum(sorted(temp)[k:]))
    

print(max(ans))

Submission status: Accepted

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

for i in range(1, min(N, K)+1):
    for j in range(i+1):
        holdings = []
        holdings.extend(V[:j])
        holdings.extend(V[N-i+j:])
        if i < K:
            holdings.sort(reverse = True)
            for _ in range(K-i):
                if holdings and holdings[-1] < 0:
                    holdings.pop()
        maxVal = max(maxVal, sum(holdings))
print(maxVal)

Submission status: Accepted

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

ans = 0
for i in range(K+1):
    for j in range(i+1):
        having = []
        having += V[:j]
        if j < i and i < N:
        	having += V[-(i-j):]
        having.sort()
        for k in range(K-i):
            if len(having) == 0: break
            if having[0] < 0:
                having.remove(having[0])
            else:
                break
        ans = max(sum(having), ans)

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):
    arr = V[:l] + ([] if r==0 else V[-r:])
    k = len(arr)
    if k > K: continue
    score = sum(arr)
    arr.sort()
    i = 0
    while k < K and i < len(arr):
      if arr[i] >= 0: break
      score -= arr[i]
      k += 1
      i += 1
    ans = max(ans, score)
print(ans)

Submission status: Accepted

Solution code:
import bisect

N, K = map(int, raw_input().split())
V = map(int, raw_input().split())

score = -1e100

M = min(N, K)
for A in range(0, M + 1):
    for B in range(0, M - A + 1):
        S = []
        if A > 0:
            S += V[:A]
        if B > 0:
            S += V[-B:]
        S.sort()
        score = max(score, sum(S) - sum(filter(lambda x: x < 0, S)[:max(0, K - A - B)]))

print score

Submission status: Accepted

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

Ntake=min(N,K)
Vsum=[]

i=0
while i<=Ntake:
    M=K-i
    j=0
    while j<=i:
        Vtake=[]
        p=1
        while p<=j:
            Vtake.append(LV[p-1])
            p+=1
        p=1
        while p<=i-j:
            Vtake.append(LV[-p])
            p+=1
        Vtake.append(0)
        Vtake.sort()
        k=0
        while k<=M-1:
            if Vtake[0]<0:
                del Vtake[0]
                k+=1
            else:
                k+=M
        Vsum.append(sum(Vtake))
        j+=1
    i+=1

print(max(Vsum))

Submission status: Accepted

Solution code:
# -*- coding:utf-8 -*-
import numpy as np

N,K = map(int,raw_input().split())

V = map(int,raw_input().split())
V = np.array(V)
ans = 0

for l in xrange(K+1):
    for m in xrange(K+1-l):
        if (l+m) > N:
            continue
        d = K-l-m
        now = 0
        s = np.array([])
        for i in xrange(l):
            now += V[i]
            s = np.append(s,V[i])
        for i in xrange(m):
            now += V[N-i-1]
            s = np.append(s,V[N-i-1])
        s = np.sort(s)
        for i in xrange(d):
            if i>=s.size:
                break
            if s[i]>0:
                break
            now -= s[i]
        
        if ans < now:
            ans = now

print int(ans)

Submission status: Accepted

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

for left in range(max_loop + 1):
    for right in range(max_loop - left + 1):
        tmp = v[:left] + v[n-right:]
        m = sorted(filter(lambda x: x< 0, tmp))[:k - left - right]
        ans = max(ans, sum(tmp) - sum(m))
print(ans)

Submission status: Accepted

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

ans = 0
for a in range(min(n, k) + 1):
    for b in range(min(n, k) - a + 1):
        li = v[:a]
        if b > 0:
            li += v[-b:]
        li.sort()
        count = 0
        while (a + b + count < k):
            if len(li) > 0 and li[0] < 0:
                count += 1
                li = li[1:]
            else:
                break
        ans = max(ans, sum(li))

print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
V=list(map(int,input().split()))
R=min(N,K)
M=0
for a in range(0,R+1):
    for b in range(0,R-a+1):
        left=V[0:a]
        right=V[N-b:N]
        getV=sorted(left+right)
        for k in range(K-(a+b)):
            if getV!=[] and getV[0]<0:
                getV=getV[1:]
        sumGetV=sum(getV)
        if sumGetV>M:
            M=sumGetV
print(M)

Submission status: Accepted

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

ans=0

for i in range(k+1):
    for j in range(k-i+1):
        Hand = []
        if i+j>n:
            break
        Hand=List[:i]
        Hand.extend(List[n-j:])
        tmp=sum(Hand)
        
        Hand.sort()
        
        for l in range(min(k-i-j,i+j)):
            if Hand[l]>=0:
                break
            tmp -= Hand[l]
        ans = max(ans,tmp)
        
print(ans)

Submission status: Accepted

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

# 左右から計min(n,k-i)個取り出す
# 0<=i<=k//2
# i個捨てる

ans = 0
# k_i回行う
for k_i in range(min(2*n+1,k+1)):
  # i個捨てる
  # k_iがnより大きい場合は捨てる個数の最低数が0より大きい
  rem_min = 0
  if k_i > n:
    rem_min = k_i - n
  for rem in range(rem_min, k_i//2+1):
    #左からj個、右から残りを取る
    for j in range(k_i-rem+1):
      #print(j)
      hand_tmp = v[:j] + v[::-1][:k_i-rem-j]
      hand_tmp.sort()
      #print(hand_tmp)
      # 小さいものからi個捨てる
      hand_tmp = hand_tmp[rem:]
      ans_tmp = sum(hand_tmp)
      if ans_tmp > ans:
        ans = ans_tmp
        
print(ans)

Submission status: Accepted

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

max_len=min(N,K)

ans=0
for l in range(max_len+1):
	for r in range(max_len-l+1):
		T=V[:l]
		if r!=0:	T+=V[-1*r:]
		suteru=K-(l+r)
		#print "l,r,T :::: ",l,r,T
		T.sort()

		for i in range( min( suteru, len(T)) ):
			if T[i]<0:
				T[i]=0
		ans=max( ans, sum(T) )

print ans

Submission status: Accepted

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

for left in range(k + 1):
    for right in range(k - left + 1):
        if left + right > n:
            break
        hold = []
        hold.extend(v[:left])
        hold.extend(v[n-right:])
        hold.sort()
        total = sum(hold)
        for i in range(min(k - left - right, left + right)):
            if 0 <= hold[i]:
                break
            total -= hold[i]
        M = max(M, total)

print(M)

Submission status: Accepted

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

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

VN = [0] + VN + [0]

score_a = 0
neg_l = []

ans = 0
for a in range(len(VN)):
    l = VN[a]
    score_a += l
    if l < 0:
        neg_l.append(l)

    score_b = 0
    neg_r = []
    for b in range(len(VN)):
        r = VN[N + 1 - b]
        score_b += r
        if r < 0:
            neg_r.append(r)

        if a + b > K or a + b > N:
            break
        else:
            negs = neg_l + neg_r
            negs.sort()
            score_cd = sum(negs[:min(len(negs), K - a - b)])
            score = score_a + score_b - score_cd
            ans = max(ans, score)
print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
 
ans=0
 
for a in range(50):
  for b in range(50):
    if a+b <= min(n,k):
      li=v[:a]+v[n-b:]
      sumv = sum(li)
      li.sort()
      for i in range(min(k-a-b,len(li))):
        if li[i] < 0:
          li[i] = 0
        else:
          break
      ans=max(ans,sum(li))
      
print(ans)

Submission status: Accepted

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

for a in range(50):
    for b in range(50):
        if a + b <= min(n,k):
            li = liv[:a] + liv[n-b:]
            sum1 = sum(li)
            li.sort()
            for i in range(min(k-a-b,len(li))):
                if li[i] < 0:
                    li[i] = 0
                else:
                    break
            ans = max(ans,sum(li))

print(ans)

Submission status: Accepted

Solution code:
# N: 宝石の数　K: 操作できる回数
N, K = map(int, input().split())
# 宝石たちの価値
V = list(map(int, input().split()))


# 解：宝石の価値の合計
ans = 0

# 宝石の数と操作できる数で小さい方を選び、その数だけ繰り返し
for n in range(1, min(K, N)+1):
    # (操作できる回数 - 操作回数), 操作回数 で小さい方を記録
    m = min(K-n, n)
    for l in range(n+1):
        # 操作回数
        r = n-l
        # 左からl番目までの宝石と右から r番目までの宝石を格納
        S = V[:l] + (V[-r:] if r != 0 else [])
        # ソートする
        S.sort()

        an = 0
        for i, a in enumerate(S):
            if i < m and a < 0:
                continue
            else:
                an += a
        ans = max(ans, an)

print(ans)

Submission status: Accepted

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

ans = 0
R = min(N, K)
for i in range(R + 1):
    for j in range(R - i + 1):
        A = []
        A += V[: i]
        if j > 0:
            A += V[- j :]
        A.sort()
        A2 = A[: K - (i + j)]
        for a in A2:
            if a < 0:
                A.remove(a)
        tmp = sum(A)
        ans = max(ans, tmp)
                
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3.4

# abc128_d

import collections
import itertools

def find_index(iterable, func):
    i = 0
    for it in iterable:
        if func(it):
            break
        i += 1
    return i

def slice_deq(deq, n):
    return itertools.islice(deq, 0, n)

def main():
    # Input
    n, k = [int(s) for s in input().split()]
    vs = (int(s) for s in input().split())
    # Get ans
    vs = collections.deque(vs)
    R = min(n, k)
    def gene_tv():
        for i in range(1, R+1):
            vs.rotate(-1)
            vs.reverse()
            for _ in range(i+1):
                temp = list(slice_deq(vs, i))
                temp.sort()
                l = find_index(temp, lambda x: x>0)
                l = min(l, k-i)
                yield sum(temp[l:])
                vs.rotate(-1)
            vs.rotate(-(i-1))
    ans = max(gene_tv())
    ans = max(ans, 0)
    # Output
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3.4

# abc128_d

import collections

def find_index(iterable, func):
    i = 0
    for it in iterable:
        if func(it):
            break
        i += 1
    return i

def main():
    # Input
    n, k = [int(s) for s in input().split()]
    vs = [int(s) for s in input().split()]
    # Get ans
    R = min(n, k)
    def gene_lr():
        for i in range(1, R+1):
            for j in range(i+1):
                yield(i-j, j)
    def gene_tv():
        for l, r in gene_lr():
            tv = 0
            temp = vs[:l] + vs[n-r:]
            temp.sort()
            i = find_index(temp, lambda x: x>0)
            s = k-(l+r)
            s = min(i, s)
            yield sum(temp[s:])
    ans = max(gene_tv())
    ans = max(ans, 0)
    # Output
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3.4

# abc128_d

import collections
import itertools

def slice_deq(deq, n):
    return itertools.islice(deq, 0, n)

def main():
    # Input
    n, k = [int(s) for s in input().split()]
    vs = (int(s) for s in input().split())
    # Get ans
    vs = collections.deque(vs)
    R = min(n, k)
    def gene_tv():
        for i in range(1, R+1):
            vs.rotate(-1)
            vs.reverse()
            for _ in range(i+1):
                tv = 0
                pps = []
                for v in slice_deq(vs, i):
                    tv += v
                    if v<0:
                        pps.append(v)
                #print(i, vs, tv, pps)
                vs.rotate(-1)
                pps.sort()
                pp = sum(pps[:k-i])
                yield tv-pp
            vs.rotate(-(i-1))
    ans = max(gene_tv())
    ans = max(ans, 0)
    # Output
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3.4

# abc128_d

def get_right(l, r):
    return l[-r:] if r!=0 else []

def main():
    # Input
    n, k = [int(s) for s in input().split()]
    vs = [int(s) for s in input().split()]
    # Get ans
    R = min(n, k)
    def gene_lr():
        for i in range(1, R+1):
            for j in range(i+1):
                yield(i-j, j)
    def gene_tv():
        for l, r in gene_lr():
            tv = 0
            pps = []
            for v in vs[:l] + vs[n-r:]:
                tv += v
                if v<0:
                    pps.append(v)
            s = k-(l+r)
            pps.sort()
            yield tv-sum(pps[:s])
    ans = max(gene_tv())
    # Output
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
#import numpy as np

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)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

def main():
    N, K = i2nn()
    V = i2nn()
    n = 0
    for l in range(K+1):
        for r in range(K+1-l):
            if l + r > N:
                continue
            v = V[:l]
            if r > 0:
                v += V[-r:]
            vp = []
            vn = []
            for t in v:
                if t > 0:
                    vp.append(t)
                elif t < 0:
                    vn.append(t)
            vn.sort()
            k = K-l-r
            n2 = sum(vn[k:]) + sum(vp)
            if n < n2:
                n = n2
    print(n)

main()

Submission status: Accepted

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

max_pick = min(K, N)
ans = 0

# 左右から取る量を決め打ち

for left in range(max_pick + 1):
    for right in range(max_pick - left + 1):
        t = v[:left] + v[N - right:]
        m = sorted(filter(lambda x: x < 0, t))[:K - left - right]
        ans = max(ans, sum(t) - sum(m))
print(ans)

Submission status: Accepted

Solution code:
import itertools
import copy


class Deque:
    def __init__(self, default_deque: list, max_count: int):
        self.in_hand = []
        self.deque = default_deque
        self.operation_count = 0
        self.max_count = max_count

    def operation(self, operation_type: str):
        if operation_type == "A":
            self.in_hand.append(self.deque[0])
            del self.deque[0]
            self.operation_count += 1
        elif operation_type == "B":
            self.in_hand.append(self.deque[-1])
            del self.deque[-1]
            self.operation_count += 1
        elif operation_type == "C":
            self.in_hand.sort()
            for i in range(self.max_count - self.operation_count):
                if self.in_hand[0] < 0:
                    del self.in_hand[0]
                else:
                    return


if __name__ == '__main__':
    max_repeat_count = int(input().split()[1])
    value_list = list(map(int, input().split()))
    point_list = []
    for repeat_count in range(max_repeat_count+1):
        operation_pattern_iter = itertools.combinations_with_replacement(["A", "B"], repeat_count)
        for operation_pattern in operation_pattern_iter:
            deque = Deque(copy.copy(value_list), max_repeat_count)
            for operation in operation_pattern:
                try:
                    deque.operation(operation)
                except:
                    break
            else:
                try:
                    deque.operation("C")
                    point_list.append(sum(deque.in_hand))
                except:
                    point_list.append(sum(deque.in_hand))
                    break
    print(max(point_list))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from heapq import heapify, heappop

def solve(N: int, K: int, V: "List[int]"):
    ans = 0
    for n_all in range(min(N, K)+1):
        for n_l in range(n_all+1):
            n_r = n_all - n_l
            tmp_v = V[:n_l] + V[N-n_r:]
            heapify(tmp_v)
            i = 0
            while len(tmp_v) > 0 and tmp_v[0] < 0 and i < K-n_all:
                _ = heappop(tmp_v)
                i += 1
            ans = max(ans, sum(tmp_v))
    print(ans)
    return

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:
#!/usr/bin/env python3
import sys


def solve(N: int, K: int, V: "List[int]"):
    ans = 0
    for n_all in range(min(N, K)+1):
        for n_l in range(n_all+1):
            n_r = n_all - n_l
            tmp_v = sorted(V[:n_l] + V[N-n_r:])
            n_neg = sum([e < 0 for e in tmp_v])
            ans = max(ans, sum(tmp_v[min(n_neg, K-n_all):]))
    print(ans)

    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:
# 累積和を使わないバージョン。時間が多分間に合わずにTLEしそう

n, k = list(map(int, input().split() ))
values = a = list(map(int, input().split() ))
ans = 0

left_pop_max = min(k, n)
for left in range(left_pop_max+1):
	picked_l = values[:left]

	# right_pop_max = min(k-left, n-left)
	right_pop_max = left_pop_max - left
	for right in range(right_pop_max+1):
		# rightが0だとvalues[0:]が配列全体になってしまうので
		if (right > 0):
			picked = picked_l + values[-right:]
		else:
			picked = picked_l

		picked.sort()
		push_max = min(k - left - right, left + right)
		push_val_sum = 0
		for i in range(push_max):
			if picked[i] >= 0:
				break
			push_val_sum += picked[i]

		new_ans = sum(picked) - push_val_sum
		ans = max(ans, new_ans)

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(1, min(N, K)+1):
    for j in range(i+1):
        take_list = []
        for k in range(j):
            take_list.append(V[k])
        for k in range(1, i-j+1):
            take_list.append(V[-k])
        take_list.sort()
        for l in range(K-i):
            if len(take_list) >= 1:
                if take_list[0] < 0:
                    take_list.pop(0)
                else:
                    break
        ans = max(ans, sum(take_list))

print(ans)

Submission status: Accepted

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

ans = 0

for m in range(min(n, k) + 1):
    for left in range(m + 1):
        right = m - left
        H = V[:left] + V[n - right:]
        H.sort()
        S = sum(H)
        remain = k - m
        for i in range(min(m, remain)):
            if H[i] > 0:
                break
            S -= H[i]
        
        ans = max(ans, S)

print(ans)

Submission status: Accepted

Solution code:
import sys
from heapq import heappop, heappush

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

    ans = 0
    for left in range(min(N, K) + 1):
        for right in range(min(N, K) - left + 1):
            heap = []
            for v in V[:left]:
                heappush(heap, v)

            for v in V[N - right:]:
                heappush(heap, v)

            cnt = left + right
            while cnt < K and len(heap) > 0:
                v = heappop(heap)
                if v >= 0:
                    heappush(heap, v)
                    break

                cnt += 1

            ans = max(ans, sum(heap))

    return ans


if __name__ == '__main__':
    print(main())

Submission status: Accepted

Solution code:
import bisect

N, K = list(map(int, input().split()))
V = list(map(int, input().split()))
ans = 0
n = min(N, K)
for A in range(n+1):
    for B in range(n-A+1):
        if not A and not B:
            continue
        if not A:
            AB = V[-B:]
        elif not B:
            AB = V[:A]
        else:
            AB = V[:A] + V[-B:]

        AB.sort()
        idx = bisect.bisect_left(AB, 0)
        k = K - (A + B)
        ans = max(ans, sum(AB[min(k, idx):]))

print(ans)

Submission status: Accepted

Solution code:
def calc_score(cnt_left, cnt_right, cnt_back, deq):
  got = deq[0:cnt_left]
  got.extend(deq[len(deq) - cnt_right:])
  sort = sorted(got)
  score = sum(sort[cnt_back:])
  return score

  
  
def main():
  n, k = [int(v) for v in input().split()]
  max_act = k

  deq = [int(v) for v in input().split()]

  high_score = 0
  for cnt_act in range(max_act + 1):
    for cnt_get in range(cnt_act + 1):
      #取得回数がでキューサイズを超えていたら実行不能
      #今後取得回数が増えるだけなのですべて実行不能なのでbreak
      if cnt_get > len(deq):
        break
        
      #戻し回数
      cnt_back = cnt_act - cnt_get
      #戻し回数が取得回数より大きいのは実行不能なのでcontinue
      if cnt_back >= cnt_get:
        continue
        
      #左取得、右取得に分割してスコアを求める
      for cnt_get_left in range(cnt_get + 1):
        cnt_get_right = cnt_get - cnt_get_left
        score = calc_score(cnt_get_left, cnt_get_right, cnt_back, deq)
        high_score = max(high_score, score)
       
  print(high_score)
  
main()

Submission status: Accepted

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

ans = 0
for i in range(k+1):
	for j in range(k-i+1):
		# print(i,j)
		L = v[:i]
		R = v[-j:]
		if len(R) == n:
			R = []
		LR = L+R+[0]
		LR.sort()
		zero_idx = min(LR.index(0),kk-i-j)
		# print(LR,zero_idx,sum(LR[zero_idx:]))
		ans = max(ans,sum(LR[zero_idx:]))
print(ans)

Submission status: Accepted

Solution code:
import sys
import collections
import copy


scan = sys.stdin.readline


def main():
    n, k = map(int, scan().rstrip().split())
    values = collections.deque([int(value) for value in scan().rstrip().split()])

    results = []

    for a in range(min(n, k) + 1):
        for b in range(min(n, k) - a + 1):
            hands = [0] * n
            v = copy.deepcopy(values)

            for _ in range(a):
                hands.append(v.popleft())
            for _ in range(b):
                hands.append(v.pop())

            hands.sort()

            c_d = 0
            for c_d in range(k - a - b):
                if hands[c_d] < 0:
                    hands[c_d] = 0
                else:
                    break
            results.append(sum(hands))
            hands = [0] * n

    results.sort(reverse=True)
    print(results[0])


if __name__ == '__main__':
    main()

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): # 右から宝石を取り出す回数
        d = deque(v) # 宝石の詰まったDeque
        num = 0 # 個々の試行によるスコア
        a = [] # heapsort用のlist
 
        cnt = 0 # 繰り返し試行、forループの代わり
        while cnt<i and len(d):
            x = d.popleft() # dequeの左端から宝石を取り出す
            heapq.heappush(a,x) # 得られたスコアを追加
            num += x # 暫定スコアを更新
            cnt += 1
        cnt = 0
        while cnt<j and len(d):
            x = d.pop()
            heapq.heappush(a,x)
            num += x
            cnt += 1
 
        sub = k-i-j # 最大試行回数から使用済み試行回数を引く
        while sub > 0 and len(a): # 残試行回数cntとスコア列aの長さが1以上の時
            y = heapq.heappop(a) # スコアが最も小さい宝石を除く
            if y <= 0: # 除いた宝石のスコアがマイナスなら
                num -= y # 最終的なスコアもマイナスにする、プラスなら取り除かなかったことにする
            sub -= 1
        
        res = max(res,num)
print(res)