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 = map(int,input().split())
V = list(map(int,input().split()))
W = [0]*N
aplus = [0]
bplus = [0]
anslist = []
for i in range(min(N,K)):
    aplus.append(aplus[i]+V[i])
    bplus.append(bplus[i]+V[N-i-1])
for i in range(min(N+1,K+1)):
    minuslist = []
    for l in range(i+1):
        if (l > 0)&(V[l-1] < 0):
            minuslist.append(V[l-1])
    for j in range(min(N-i+1,K+1)):
        if i + j > K:
            break
        if (j > 0)&(V[-j] < 0):
            minuslist.append(V[-j])
        minuslist.sort()
        if K-i-j > len(minuslist):
            anslist.append(aplus[i]+bplus[j]-sum(minuslist))
        else:
            minus = 0
            anslist.append(aplus[i]+bplus[j])
            for k in range(K-i-j):
                minus += minuslist[k]
                anslist.append(aplus[i]+bplus[j]-minus)
print(max(anslist))

Submission status: Accepted

Solution code:
def subsolve(pop, push):
    ans = 0
    for i in range(pop + 1):
        rpop, lpop = i, pop - i
        r = [] if rpop == 0 else vs[-rpop:]
        l = [] if lpop == 0 else vs[:lpop]
        ans = max(ans, sum(sorted(r + l)[push:]))
    return ans


NEGINF = -float("inf")
n, k = map(int, input().split())
vs = list(map(int, input().split()))
ans = 0

for k_ in range(k + 1):
    for i in range(k_ + 1):
        push, pop = i, k_ - i
        if push > pop or pop > n:
            continue
        ans = max(ans, subsolve(pop, push))


print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
s = 0
for i in range(min(K, N)+1):
    r = K - i
    for j in range(i+1):
        k = i - j
        Q = sorted(V[:j] + V[N-k:])
        m = sum([q < 0 for q in Q])
        s = max(s, sum(Q[min(m, r):]))
print(s)

Submission status: Accepted

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

def dispose(disposeList, tms):
    disposeList.sort()
    i = 0
    while i < tms:
        if disposeList[i] < 0:
            disposeList[i] = 0
            i += 1
        else:
            return disposeList
        
    return disposeList
    
res = 0
for take in range(min(N,K)+1):
    for left in range(take+1):
        right = take - left
        my_V = [V[i] for i in range(left)] + [V[-i-1] for i in range(right)]
    
        my_V = dispose(my_V, min(take, K-take))
        res = max(res, sum(my_V))
        
print(res)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[30]:


import sys
#import numpy as np
#import itertools
input = sys.stdin.readline
N, K = map(int, input().split())
V = list(map(int, input().split()))


# In[36]:


#print(N, K)
#print(V)


# In[ ]:


"""
6 4
-10 8 2 1 2 6
"""


# In[46]:


ans = 0
for l in range(K+1):
    if l > N:
        continue
    for r in range(K+1-l):
        if l+r>K or l+r>N:
            continue
        d = K-(l+r)
        picked = V[:l] + V[-r:] if r != 0 else V[:l]
        #print("l:{}, r:{}, picked{}".format(l, r, picked))
        sp = sorted(picked)
        now = sum(picked)
        #print(sp)
        for i in range(d):
            if i >= len(picked):
                break
            if sp[i] > 0:
                break
            now -= sp[i]
        ans = max(ans, now)
print(ans)
        
"""
if N < K:
    scs = []
    for i in range(K-N):
        scs.append(sorted(V[i:]))
    s = max(scs)
else:
    scs = []
    for i in range(K//2):
        #print("{}個返す".format(i))
        scss = []
        for j in range(K+1-i):
            #print("左から{}個　右から{}個/{}".format(j,K-j-i, K-i))
            if j == K-i:
                choices = V[:j]
            else:
                choices = V[:j] + V[-K+j+i:]
            #print(choices)
            #print(sorted(choices)[i:])
            scss.append(sum(sorted(choices)[i:]))
        scs.append(max(scss))
    s = max(scs)
    s = 0 if s<0 else s
print(s)
"""


# In[ ]:

Submission status: Accepted

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

if K <= 2:
    print(max(V[0], V[-1], 0))
    quit()


ans = 0
for a in range(min(N, K)+1):
    for b in range(min(N-a, K-a)+1):
        V_ = sorted(V[:a] + V[-b:]) if b >= 1 else sorted(V[:a])
        tmp = K - (a+b)
        curMinus = 0
        for v in V_:
            if v < 0 and tmp > 0:
                tmp -= 1
                curMinus += -v
        ans = max(ans, sum(V_)+curMinus)

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) + 1 - a):
        juels = sorted(V[:a] + V[len(V)-b:])
        if not juels:
            continue
        cd = K - a - b
        now = sum(juels)
        for i in range(min(len(juels), cd)):
            if juels[i] < 0:
                now -= juels[i]
        ans = max(ans, now)
print(ans)

Submission status: Accepted

Solution code:
[input_n, input_k] = map(int, input().split())

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

max_value = 0

for a in range(min(input_n, input_k) + 1):
    for b in range(min(input_n, input_k) - a + 1):
        if (b != 0):
            hold_jewelries = input_v[:a] + input_v[-b:]
        else:
            hold_jewelries = input_v[:a]
        hold_jewelries = sorted(hold_jewelries)

        remove_length = input_k - a - b
        hold_minus = sum(1 for value in hold_jewelries if value < 0)

        hold_value = sum(hold_jewelries[min(hold_minus, remove_length):])

        if (hold_value > max_value):
            max_value = hold_value

print(max_value)

Submission status: Accepted

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

m = k // 2 + (k % 2)

a = [0] * (n+1)
d = [0] * (n+1)

a[0] = 0
d[0] = 0
for i in range(n):
    a[i+1] = a[i] + v[i]
    d[i+1] = d[i] + v[n-1-i]

w = []
for i in range(n):
    w.append([v[i], i])

w.sort()

ans = 0

p = min(n, k)
for L in range(p + 1):
    for R in range(p + 1 - L):
        #print(L, R)
        temp = a[L] + d[R]
        b = min(L + R, k - L - R)
        c = 0
        while b > 0:
            if w[c][0] >= 0:
                break
            if w[c][1] < L or w[c][1] > n - 1 - R:
                #print(w[c][1], L, R)
                temp -= w[c][0]
                b -= 1
            c += 1
        #print(L, R, temp, b)
        ans = max(ans, temp)

print(ans)

Submission status: Accepted

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

def solve():
  n,k = (int(i) for i in input().split())
  v = list(int(i) for i in input().split())
  ans = 0
  
  for atimes in range(min(n,k+1)):
    for btimes in range(min(n-atimes+1,k-atimes+1)):
      if [atimes,btimes] == [0,0]:continue
      
      getjewel = v[0:atimes]+v[n-btimes::]
      
      getjewel.sort()
      deletevalue = 0
      maxdeletetimes = k-atimes-btimes
      #print(getjewel,maxdeletetimes)
      for i in range(min(len(getjewel),maxdeletetimes)):
        if getjewel[i] <= 0:
          deletevalue -= getjewel[i]
      ans = max(sum(getjewel)+deletevalue,ans)
  print(ans)
solve()

Submission status: Accepted

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

for i in range(min(n,k)+1):
    for j in range(min(n,k)-i+1):
        d=k-i-j
        l=v[0:i]
        r=v[n-j:n]
        p=r+l
        q=[]
        s=sum(p)
        for x in p:
            if x<0:
                q.append(x)
        q.sort()
        for x in range(min(len(q),d)):
            s-=q[x]
        ans.append(s)
        
print(max(ans))

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
v = list(map(int, input().split()))
t = min(n,k)
ans = 0
for i in range(t+1):
  for j in range(t-i+1):
    hnd = v[:i]+v[-j:]*(j!=0)
    hnd.sort(reverse=True)
    for _ in range(min(k-i-j,len(hnd))):
      if hnd[-1] < 0:
        hnd.pop()
      else:
        break
    cur = sum(hnd)
    if ans<cur:
      ans=cur
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import copy
import collections
from bisect import bisect_left
from bisect import bisect_right
	
def main():
	N, K = map(int, input().split(" "))
	V = list(map(int, input().split(" ")))
	
	V_tmp = copy.deepcopy(V)
	ans = 0
	for L in range(K+1):
		for R in range((K+1)-L):
			V = copy.deepcopy(V_tmp)
			gets = []
			tmp = 0
			
			for i in range(L):
				if len(V) > 0:
					tmptmp = V.pop(0)
					tmp += tmptmp
					if tmptmp < 0:
						gets.append(tmptmp)
					
			for i in range(R):
				if len(V) > 0:
					tmptmp = V.pop(-1)
					tmp += tmptmp
					if tmptmp < 0:
						gets.append(tmptmp)
					
			#print(gets)
			for i in range(K-L-R):
				if len(gets) == 0:
					break
				gets.sort()
				tmp = tmp + (-1 * gets.pop(0))
				
			if tmp > ans:
				ans = tmp
				
	print(ans)
	
	
	
if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
import sys
inputs = sys.stdin.readline
N, K= map(int,inputs().split())
V = list(map(int,inputs().split()))

maxim = 0
if K <= 2*N - 1:
	for i in range(0,K+1):
		for j in range(i+1):
			if j == i:
				a = V[:j] + [0]
			else:
				a = V[:j] + V[j-i:] + [0]
			a.sort()
			b = a.index(0)
			if b <= K - i:
				maxim = max(sum(a[b:]),maxim)
			else:
				maxim = max(sum(a[K-i:]),maxim)
else:
	V.append(0)
	V.sort()
	maxim = sum(V[V.index(0):])
print(maxim)

Submission status: Accepted

Solution code:
#coding:utf-8
N,K=map(int,raw_input().split())
V=map(int,raw_input().split())
VR=list(reversed(V))
ans=-10**8
for l in range(K+1):
    for r in range(K+1):
        if l+r>K or l+r>N:continue
        d=K-l-r
        buf=V[:l]; buf+=VR[:r]
        buf.sort()
        buf.reverse()
        for i in range(d):
            if len(buf)>0 and buf[-1]<0:buf.pop()
        ans=max(ans,sum(buf))
print(ans)

Submission status: Accepted

Solution code:
from collections import deque, _heapq
N, K = map(int, input().split())
V = deque(map(int, input().split()))

class Money:
    def __init__(self):
        self.yen = 0
        self.red = []

    def value(self):
        return self.yen + sum(self.red)

    def add(self, yen):
        if yen >= 0:
            self.yen += yen
        else:
            self.red.append(yen)

    def remove(self, yen):
        if yen >= 0:
            self.yen -= yen
        else:
            self.red.remove(yen)

#mny = Money()
def get(cnt, mny, lstop, rstop):
    ans = mny.value()

    if cnt <= 0:
        return ans

    if len(V) > 0:

        if lstop == 0:
            w = V.popleft()
            mny.add(w)
            ans = max(ans, get(cnt-1, mny, lstop, rstop))
            mny.remove(w)
            V.appendleft(w)
        elif lstop > 0:
            lstop -= 1

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

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

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

        mny.red.append(w)    

    return ans

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from sys import setrecursionlimit
from collections import deque
import heapq

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

ans = 0
D = V_array + V_array
# print(D)

for pop_count in range(K, 0, -1):
    if pop_count > N:
        continue
    append_count = K - pop_count
    for pop_index in range(N - pop_count, N + 1, 1):
        popped_object = D[pop_index:pop_index + pop_count]
        popped_object.sort()
        popped_sum = sum(popped_object)
        for i in range(min(pop_count, append_count)):
            if popped_object[i] < 0:
                popped_sum -= popped_object[i]
            else:
                break
        ans = max(ans, popped_sum)

print(ans)

Submission status: Accepted

Solution code:
ans=0
#n=int(input())
n,k=map(int,input().split())
v=[int(i) for i in input().split()]
b=sum(v)
f=[0]*(n+1)
ne=[i for i in v if i<0]
acn=[0]*(1+len(ne))
pre=0
for i in range(n):
    f[i+1]=f[i]+v[i]
    if i<len(ne):
        acn[i+1]=acn[i]+ne[i]

for lp in range(k+1):
    for rp in range(k+1):
        for back in range(lp+rp+1):
            if lp+rp+back>k or lp+rp>n:# or back>len(ne):
                break
            tmp=v[:lp]+v[len(v)-rp:]
            tmp.sort(reverse=True)
            ans=max(ans,sum(tmp[:len(tmp)-back])) 
print(ans)

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline
n, k = map(int, input().split())
v_list = list(map(int, input().split()))
ans = 0
for i in range(1, min(n,k)+1):
    for j in range(i+1):
        cnt = k - i
        tmp_list = []
        if j == 0:
            tmp_list += v_list[-i:]
        elif j == i:
            tmp_list += v_list[:i]
        else:
            tmp_list += v_list[:j]
            tmp_list += v_list[-(i-j):]
        tmp_list.sort()
        tmp_sum = sum(tmp_list)
        for tmp in tmp_list:
            if cnt <= 0:
                break
            if tmp < 0:
                tmp_sum -= tmp
                cnt -= 1
            else:
                break
        ans = max(ans, tmp_sum)
print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect
n,K = (int(i) for i in input().split())
v = [int(i) for i in input().split()]
ans = 0
for i in range(min(n,K)+1):
    for j in range(i+1):
        z = []
        for k in range(j): z.append(v[k])
        for k2 in range(i-j): z.append(v[-k2-1])
        z.sort()
        ans = max(ans,sum(z[min(bisect(z,0),K-i):]))
print(ans)

Submission status: Accepted

Solution code:
import copy
import heapq
from collections import deque
N, K = list(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-i, K-i) + 1):
        s = V[:i] + V[N-j:]
        s.sort()
        m = 0
        for x in range(min(K - i - j, len(s))):
            if s[x] < 0:
                m += s[x]
            else:
                break

        ans = max(ans, sum(s) - m)

print(ans)

Submission status: Accepted

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

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

ans = 0
# 左からl個(0..K)
for l in range(K + 1):
    # 右からはr個(0..K-l)
    for r in range(K - l + 1):
        # N個よりは取れない
        if l + r > N:
            continue
        # 残りの操作数
        d = max(0, K - (l + r))

        # 合計値
        s = sum(V[:l]) + sum(V[N - r:])
        # 手元のマイナス
        neg = filter(lambda x: x < 0, V[:l] + V[N - r:])
        neg = list(neg)
        neg.sort()
        for i in range(d):
            if i < len(neg):
                s -= neg[i]

        # print(s)
        ans = max(ans,s)

print(ans)

Submission status: Accepted

Solution code:
import itertools
import numpy as np
import copy

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

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

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

	maxScore = 0
	for candidate in allCandidates:
		have = []
		vs = copy.deepcopy(Vs)
		exceptFlag = False
		for k in candidate:
			if k == 0:
				try:
					have.append(vs[0])
					del vs[0]
				except:
					exceptFlag = True
					break
			if k == 1:
				try:
					have.append(vs[-1])
					del vs[-1]
				except:
					exceptFlag = True
					break
			if k == -1:
				try:
					if have[np.argmin(have)] < 0:
						del have[np.argmin(have)]
				except:
					exceptFlag = True
					break
		if not exceptFlag:
			score = sum(have)
			if score > maxScore:
				maxScore = score

	print(maxScore)

if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
v=[int(i) for i in input().split()]
r=min(n,k)
ans=0
for a in range(r+1):
    for b in range(r-a+1):
        if b>=1:
            q=v[:a]+v[-b:]
        else:
            q=v[:a]
        t=k-a-b
        m=0
        for i in sorted(q):
            if i<0 and t>0:
                m+=abs(i)
                t-=1
        ans=max(ans,m+sum(q))
print(ans)

Submission status: Accepted

Solution code:
def solve(k, koho, cho=[], syo=0):
    if syo == 2:
        lenc=len(cho)
        for i in range(min(k,lenc)):
            mn = min(cho)
            if mn < 0:
                cho.remove(mn)
            else:
                break
        return sum(cho)
    if syo == 1:
        koho = koho[::-1]
    re = []
    lenk = len(koho)
    for i in range(min(k, lenk)+1):
        re.append(solve(k - i, koho[i:], cho+koho[:i], syo + 1))
    return max(re)

n, k = map(int, input().split())
vs = list(map(int, input().split()))
print(solve(k, vs))

Submission status: Accepted

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

rich = 0
# bring k jewels
for k in range(1, min(K+1, N+1)):
    for rot in range(k+1):
        jewels = (V[-rot:] + V[:-rot])[:k]
        jewels.sort()
        neg = [i < 0 for i in jewels].count(True)
        # return r jewels
        for ret in range(min(neg+1,K-k+1)):
            rich = max(sum(jewels[ret:]), rich)

print(rich)

Submission status: Accepted

Solution code:
#ABC128D-equeue.py

from sys import stdin

input = stdin.readline

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

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


print(max(sumList))

Submission status: Accepted

Solution code:
def value(k1,k2,k,D):
    if k2 == 0:
        v0 = D[:k1] + [0]
    else:
        v0 = D[:k1] + D[-(k2):] + [0]
    v0.sort()  # 取り出す宝石の価値リスト
    n_neg = v0.index(0)  # 負価値の数
    k0 = k - (k1+k2)  # 残り操作回数
    if n_neg <= k0:
        ans = sum(v0[n_neg:])
    else:
        ans = sum(v0[k0:])
    #print(k1,k2,n,k0,v0, ans)
    return ans

n,k = map(int,input().split(' '))
D = list(map(int,input().split(' ')))
score = 0
k1 = 0
while k1 < min(k+1,n+1):
    k2 = 0
    while k2 + k1 < min(k+1,n+1):
        v = value(k1,k2,k,D)
        if v > score:
            score = v
            #print(k1,k2)
            #print(score)
        k2 += 1
    k1 += 1
print(score)

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 k in range(1,K+1):
    for i in range(k+1):
        R = V[-(k-i):]
        if len(R) == N:
            R = []
        # print(R)
        L = V[:i]+R+[0]
        L.sort()
        zero_index = min(L.index(0),KK-k)
        res = sum(L[zero_index:])
        ans = max(ans,res)
print(ans)

Submission status: Accepted

Solution code:
import heapq
N, K = map( int, input().split())
V = list(  map( int, input().split()))
ans = 0
for i in range(N+1):
    for j in range(N+1):
        if i + j > K or i + j > N:
            break
        cnt = i+j
        if j == 0:
            q = V[:i]
            now = sum(q)
            heapq.heapify(q)
            while q and (cnt < K):
                t = heapq.heappop(q)
                if t >= 0:
                    break
                else:
                    now += -t
                    cnt += 1
        else:
            q = V[:i] + V[-j:]
            now = sum(q)
            heapq.heapify(q)
            while q and (cnt < K):
                t = heapq.heappop(q)
                if t >= 0:
                    break
                else:
                    now += -t
                    cnt += 1
        if ans < now:
            ans = now
print( ans)

Submission status: Accepted

Solution code:
from collections import deque

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

numofget=min(N,K)
tmp=[]
for i in range(numofget+1):
    A,B=i,numofget-i
    for j in range(B+1):
        q=deque(V)
        bag=[]
        for a in range(A):
            bag.append(q.popleft())
        for b in range(j):
            bag.append(q.pop())
        for _ in range(K-(A+j)):
            if len(bag)>0 and min(bag)<0:
                bag.remove(min(bag))
        tmp.append(sum(bag))
print(max(tmp))

Submission status: Accepted

Solution code:
def main():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    ans = 0
    for l in range(K + 1):
        for r in range(K - l + 1):
            if l + r > N:
                continue
            d = K - l - r
            s = V[:l] + V[N - r:N]
            now = 0
            now += sum(s)
            s.sort()
            for i in range(d):
                if i >= len(s):
                    break
                if s[i] > 0:
                    break
                now -= s[i]
            ans = max(ans, now)
    print(ans)


main()

Submission status: Accepted

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

ans = 0
for num_a in range(min(N,K) + 1):
    for num_b in range(min(N-num_a,K-num_a) + 1):
        if num_b >= 1:
            temp_v = V[:num_a] + V[-num_b:]
        else:
            temp_v = V[:num_a]
        t = K - num_a - num_b
        s = 0
        for vv in sorted(temp_v):
            if vv < 0 and t > 0:
                s += -vv
                t -= 1
        ans = max(ans, sum(temp_v) + s)
        
print(ans)

Submission status: Accepted

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

maxsum = -10**13
for i in range(min(n+1,k+1)):
    for j in range(min(n+1-i,k+1-i)):
        su = (V[:i] + V[:n-j-1:-1])
        su.sort()
        sumsu = sum(su)
        #print("i,j:",i,j,su)
        if k-i-j > 0:
            for l in range(k-i-j):
                if len(su) > l and su[l] < 0: sumsu -= su[l]
        maxsum = sumsu if maxsum < sumsu else maxsum
print(maxsum)

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)
        num = 0
        a = []

        cnt = 0
        while cnt<i and len(d):
            x = d.popleft()
            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):
            y = heapq.heappop(a)
            if y <= 0:
                num -= y
            sub -= 1
        
        res = max(res,num)
print(res)

Submission status: Accepted

Solution code:
from collections import deque

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

ans = 0 # ans >= 0
for l in range(K+1):
    for r in range(K+1-l):
        if l+r > N: break
        ll_max = K+1-l-r
        for ll in range(ll_max):
            rr = K-l-r-ll
            if not all([0<=val<=N for val in [l,r]]):
                break
            # print("l,ll,r,rr:", l,ll,r,rr)
            if ll>N: ll=N
            if rr>N: rr=N
            l_vs = sorted(vs[:l])
            r_vs = sorted(vs[N-r:])
            ans = max(ans, sum(l_vs)+ sum(r_vs))

            l_remain = l_vs[ll:]
            r_remain = r_vs[rr:]
            # print("l_remain:", l_remain)
            # print("r_remain:", r_remain)
            ans = max(ans, sum(l_remain) + sum(r_remain))

print(ans)

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-A+1):
        C=K-(A+B)
        have=[]
        have.extend(v[:A])
        have.extend(v[N-B:])
        have.sort()
        for c in range(C):
            if len(have)>0:
                if have[0]<0:
                    have.pop(0)
                else:
                    break
        ans=max(ans,sum(have))

print(ans)

Submission status: Accepted

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

ans = 0

R = min(N, K)
for A in range(R+1):
  for B in range(R-A+1):
    C = K-(A+B)
    have = []
    have.extend(v[:A])
    have.extend(v[N-B:])
    have.sort()
    for c in range(C):
      if len(have) > 0:
        if have[0] < 0:
          have.pop(0)
        else:
          break
    ans = max(ans, sum(have))

print(ans)

Submission status: Accepted

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

ans = 0
cnt = 0
for i in range(n+1):
    for j in range(n+1):
        if i + j > n or i + j > k:
            continue
        if j == 0:
            a = v[:i]
        else:
            a = v[:i] + v[-j:]
        tmp = sum(a)
        a.sort()
        for x in range(min([k-(i+j), i+j])):
            if a[x] >= 0:
                break
            tmp -= a[x]
        ans = max([ans, tmp])
        cnt += 1

print(ans)

Submission status: Accepted

Solution code:
def take(n, lis):
    if n >= len(lis):
        return lis
    if n <= 0:
        return []
    else:
        return lis[:n]


n, k = list(map(int, input().split(" ")))
vs = list(map(int, input().split(" ")))
if n == 1:
    print(max(0, vs[0]))
    exit()
if k == 1:
    print(max(0, vs[0], vs[-1]))
    exit()
scores = []
score = 0
length = min(n, k)
for gets in range(length + 1):
    for left in range(gets + 1):
        right = gets - left
        retnum = k - gets
        get_list = take(left, vs) + take(right, vs[::-1])
        minus = sorted([get for get in get_list if get <= 0])
        score = sum(get_list) - sum(take(retnum, minus))
        scores.append(score)
print(max(0, *scores))

Submission status: Accepted

Solution code:
n,k=list(map(int,input().split()))
v=list(map(int,input().split()))
#左から取れる個数はL=0~min(n,k)
#右から取れる個数はR=0~(min(n,k)-L)
#戻す個数はk-L-R個まで少ない方から負の価値の石を返す
ans=0
for L in range(min(n,k)+1):
    for R in range(min(n,k)-L+1):
        v_get=v[0:L]+v[n-R:n]
        v_get.sort()
        D=0
        for i in v_get:
            if D==k-L-R:
                break
            if i>=0:
                break
            D+=1
        if D==0:
            total=sum(v_get)
        else:
            total=sum(v_get[D:])
        if total>ans:
            ans=total
print(ans)

Submission status: Accepted

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

ans = 0

for left in range(K + 1):
    for right in range(K - left + 1):
        if left + right > N:
            break
        items = list(D[0:left])
        items.extend(D[::-1][0:right])
        dis = K - (left + right)
        i = 0
        items = sorted(items, reverse=True)
        while True:
            ans = max(ans, sum(items))
            if i < dis and len(items) > 0:
                i += 1
                items.pop()
                continue
            else:
                break

print(ans)

Submission status: Accepted

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

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

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

maxans = 0
for l in range(K+1):
    for r in range(K-l+1):
        d = K - l- r
        if l+r > N:
            break
        hand = []
        hand.extend(V[:l])
        if r != 0:
            hand.extend(V[-r:])
        hand.sort()
        ans = sum(hand)

        for i in range(d):
            if len(hand) <= i+1:
                break
            if hand[i] < 0:
                ans -= hand[i]
        
        if ans > maxans:
            maxans = ans

print(maxans)

Submission status: Accepted

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

Submission status: Accepted

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

for n_get in range(1, min(N, K)+1):
    for a in range(n_get+1):
        b = n_get - a
        temp = V[:a] + V[N-b:]
        temp = sorted(temp)
        rem = max(0, K - n_get)
        i = 0
        while rem > 0 and i < n_get:
            if temp[i] >= 0:
                break
            rem -= 1
            i += 1
        ans = max(ans, sum(temp[i:]))

print(ans)