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


def main():
    # 読み込み回数が多い場合
    input = sys.stdin.readline
    # 複数
    N, K = map(int, input().split())

    # リスト読み込み
    V_A = [inp for inp in map(int, input().split())]
    V_B = V_A.copy()[::-1]
    
    ret = 0
    for A in range(min(K + 1, N + 1)):
        for B in range(min(K - A + 1, N - A + 1)):
            left_jewels = V_A.copy()[:A]
            right_jewels = V_B.copy()[:B]

            if len(left_jewels) >= len(right_jewels):
                jewels = left_jewels
                jewels.extend(right_jewels)
            else:
                jewels = right_jewels
                jewels.extend(left_jewels)
            jewels.sort()

            score = sum(jewels)

            for i in range(min(K - A - B, len(jewels))):
                jewel = jewels[i]
                if jewel < 0:
                    score -= jewel
                else:
                    break
                    
            ret = max(ret, score)
                
    print(ret)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def solve():
    N, K, *V = map(int, open(0).read().split())
    
    AB_MAX = min(N, K)
    val = []
    for left in range(AB_MAX+1):
        for right in range(AB_MAX-left+1):
            get = V[:left] + V[-right:] if right != 0 else V[:left]
            get.sort()
            i = K - left - right
            if get:
                while get[0] < 0 and 0 < i:
                    get = get[1:]
                    i -= 1
                    if not get:
                        break
            val.append(sum(get))
    print(max(val))


if __name__ == '__main__':
    solve()

Submission status: Accepted

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

    for left in range(K+1):
        for right in range(K+1):
            if left + right > K:
                continue
            tmp = []
            for i in range(min(N, left)):
                tmp.append(V[i])

            for j in range(max(left,N-right),N,1):
                tmp.append(V[j])

            nokori = K - left - right
            tmp.sort()
            tmp_sum = sum(tmp)
            for k in range(min(nokori, len(tmp))):
                if tmp[k] < 0:
                    tmp_sum -= tmp[k]

            ans = max(ans, tmp_sum)

    print(ans)





if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def sum0(L, k):
  c = 0
  for i in L:
    if i>=0:
      c += i
    else:
      if k>0:
        k -= 1
      else:
        c += i
  return c

n, k = map(int, input().split())
V = list(map(int, input().split()))
m = min(n, k)
ans = 0
for i in range(m+1):
  for j in range(m+1-i):
    L = sorted(V[:i] + V[n-j:])
    ans = max(ans, sum0(L, k-(i+j)))
print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect

n, k = map(int, input().split())
*v, = map(int, input().split())
candidate = []
for i in range(k+1):
    for j in range(k-i+1):
        if i + j >= n:
            candidate.append(v)
        elif j == 0:
            candidate.append(v[:i])
        else:
            candidate.append(v[:i]+v[(-1)*j:])
ans = 0
for cand in candidate:
    cand.sort()
    idx = bisect(cand, -1)
    rem = k-len(cand)
    p = min(idx, rem)
    if ans < sum(cand[p:]):
        a = cand
        b = p
        ans = sum(cand[p:])
print(ans)

Submission status: Accepted

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

for i in range(0, min(n+1, k+1)):
    for j in range(0, min(n+1-i, k+1-i)):
        x = k - i - j
        tmp = v[:i] + vv[:j]
        tmp.sort()
        #print(tmp, i, j, x)
        t = 0
        for q in range(len(tmp)):
            if tmp[q] < 0 and (q+1) <= x:
                pass
            else:
                t += tmp[q]
        #print(t)
        ans = max(ans, t)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
from bisect import insort_left

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

answer = 0
A = 0
while A <= min(N,K):
    B = 0
    while A + B <= min(N,K):
        have = []
        for i in range(A):
            insort_left(have, V[i])
        for i in range(B):
            insort_left(have, V[-(i+1)])

        have = deque(have)

        throw = min(K - (A + B), len(have))
        for _ in range(throw):
            tmp = have.popleft()
            if tmp > 0:
                have.append(tmp)
                break

        answer = max(answer, sum(have))
        B += 1
    A += 1

print(answer)

Submission status: Accepted

Solution code:
import heapq

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

min_d = -10**9

for k in range(min(K+1, N+1)):
    for a in range(0, k+1):
        b = k - a
        hq = d[: a] + d[N - b: N]
        heapq.heapify(hq)
        kk = k
        while kk < K and hq != []:
            hq_d = heapq.heappop(hq)
            if hq_d >= 0:
                heapq.heappush(hq,hq_d)
                break
            else:
                kk += 1
        min_d = max(min_d, sum(hq))        
        
print(min_d)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
N,K,*V = map(int,read().split()) #*Vで行単位の配列を得られる。
#print(V)

vals = [] #valuesの略。

for L in range(N+1): #左
    for R in range(N+1): #右
        if L+R > N: #このbreakで、うまく左右からとれる。
            break
        get = V[:L] + V[N-R:]
        rest = K - (L+R) #ridの代わりにrest。汎用性がある。
        if rest < 0:
            break
        get.sort(reverse=True) #逆順にしてpop()で抜き出している。
        for _ in range(min(len(get),rest)): #indexを用いないforループは_で。徹底。
            if get[-1] < 0:
                get.pop()
            else:
                break
        vals.append(sum(get)) #最小値を求める際はmax(answer, buffer)ではない。一度配列。

answer = max(vals)
print(answer)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

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

answer = 0

for i in range(min(N, K)+1):
  for j in range(i+1):
    U = V[:j]+V[N-(i-j):]
    U.sort()
    rid = K - i
    for k in range(len(U)):
      if rid == 0:
        break
      if U[k] < 0:
        rid -= 1
        U[k] = 0
      else:
        break
    answer = max(sum(U), answer)   
print(answer)

Submission status: Accepted

Solution code:
n,k = map(int, input().split( ))
v = list(map(int, input().split( )))
import bisect
ans = 0
for i in range(k):
    for j in range(min(n-i,k-i)+1):#+1
        u = v[:j]+v[n-i:]
        u.sort()
        ind = bisect.bisect_left(u,0)###
        t = min(ind, k-i-j)
        sm = sum(u[t:])
        if ans < sm:
            #print(i,j,t)
            ans = sm
    
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(N):
    for j in range(i,N+1):
        if i+N-j<=K:
            k=K-(i+N-j)
            s=V[:i]+V[j:]
            s.sort()
            c=0
            for t in s:
                if k>=1 and t<0:
                    k-=1
                else:
                    c+=t
            ans=max(c,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+1, K+1)):
    for j in range(i+1):
        values = sorted(V[:j] + V[N-(i-j):])
        k = i+1
        while k <= K and len(values) > 0 and values[0] < 0:
            k += 1
            values.pop(0)
        ans = max(ans, sum(values))
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(K+1):
    left = []
    if i != 0:
        left = V[:i]
    for j in range(K-i+1):
        right = []
        if j == 0:
            right = []
        elif (N-i) == 0:
            right = []
        elif i+j > N:
            continue
        else:
            right = V[-j:]
        for k in range(K-i-j+1):
            if k > i+j:
                continue
            sort_merge = sorted(left+right)
            if sum(sort_merge[k:]) == 990000000:
                print(sort_merge)
            ans = max(ans, sum(sort_merge[k:]))

print(ans)

Submission status: Accepted

Solution code:
import heapq
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for k in range(min(K+1, N+1)):
    for i in range(k+1):
        tmp = 0
        tmp2 = []
        heapq.heapify(tmp2)

        for j in range(k-i):
            tmp += V[j]
            if V[j] < 0:
                heapq.heappush(tmp2, V[j])
        for j in range(i):
            tmp += V[N-1-j]
            if V[N-1-j] < 0:

                heapq.heappush(tmp2, V[N-1-j])

        for j in range(min(k, K-k)):
            if len(tmp2) == 0:
                break
            tmp -= heapq.heappop(tmp2)
        ans = max(tmp, ans)


print(ans)

Submission status: Accepted

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

import numpy as np

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

v = np.array(v)

ans = 0
if n <= k:
    ans = v[v>0].sum()
else:
    for i in range(k+1):
        for j in range(k-i+1):
            if j == 0:
                take = v[0:i]
            else:
                take = np.append(v[0:i], v[-j:])
            take.sort()
            throw_num = k-i-j
            throw_num = min(throw_num, len(take[take<0]))
            su = take[throw_num:].sum()
            if su > ans:
                ans = su
print(ans)

Submission status: Accepted

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(1000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n,k = LI()
v = LI()
ans = -inf
for l in range(min(n,k)+1):
    for r in range(min(n,k)+1 - l):
        lst = v[:l] + v[n-r:]
        lst.sort()
        m = len(lst)
        s = sum(lst)
        t = k - (r + l)
        for i in range(min(m,t)):
            if lst[i] < 0:
                s -= lst[i]
        ans = max(ans,s)
print(ans)

Submission status: Accepted

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

act = min(N, K)

ans = - 10 ** 19
for i in range(act + 1):
  for a in range(i + 1):
    for b in range(i - a + 1):
      itm = []
      itm += V[:a]
      itm += V[N-b:]
      itm.sort()
      idx = bisect_left(itm, 0)
      prize = sum(itm[min(idx, K - a - b):])
      ans = max(ans, prize)
print(ans)

Submission status: Accepted

Solution code:
import heapq
N,K = map(int,input().split(' '))
Vn = list(map(int,input().split(' ')))
max_sum = 0
max_get = min(N+1,K+1)
for i1 in range(1,max_get):# 取る個数を決める
    for i2 in range(i1): #K の場所を動かす
        minus_queue = []
        forward_num = i1 - i2
        back_num = i2
        all_sum = 0
        #前方のlist
        forward_list = Vn[0:forward_num]
        back_list = Vn[N-back_num:N]
        for val in forward_list:
            all_sum += val
            if val < 0:
                minus_queue.append(val)
        #後方のlist
        for val in back_list:
            all_sum += val
            if val < 0:
                minus_queue.append(val)
        heapq.heapify(minus_queue)
        dequeue_num = K-i1
        for i3 in range(dequeue_num): #戻すKを決める
            if len(minus_queue) > 0:
                val = heapq.heappop(minus_queue) 
                all_sum -= val
            else:
                break
        max_sum = max(max_sum,all_sum)
print(max_sum)

Submission status: Accepted

Solution code:
from collections import deque
import itertools
n,k=map(int,input().split())
v=deque(list(map(int,input().split())))
a=0
ans=0
while a<=n and a<=k:
  w=deque(itertools.islice(v,0,None))
  b=0
  A=deque([0])
  for i in range(a):
    p=w.popleft()
    A.append(p)
  while a+b<=n and a+b<=k:
    x=deque(itertools.islice(w,0,None))
    B=deque(itertools.islice(A,0,None))
    for j in range(b):
      B.append(x.pop())
    B=deque(sorted(B))
    c=0
    while c<k-a-b and B[0]<0 and c<a+b:
      B.popleft()
      c=c+1
    V=sum(B)
    if V>ans:
      ans=V
    b=b+1
  a=a+1
print(ans)

Submission status: Accepted

Solution code:
import heapq


def one_direction(a, j):
    res = 0
    for u in range(0, min(len(a)+1,j+1)):
        l = []
        heapq.heapify(l)
        sum = 0
        for w in range(u):
            sum += a[w]
            heapq.heappush(l, a[w])
        for y in range(j-u):
            if len(l) > 0:
                f = heapq.heappop(l)
                if f < 0:
                    sum -= f
                else:
                    break
        res = max(res, sum)
    return res




n,k = [int(_) for _ in input().split()]
v = [int(_) for _ in input().split()]
a = []
dp = [[0 for _ in range(k+1)] for _ in range(n+1)]
for i in range(1, n+1):
    x = v.pop()
    a.append(x)
    for j in range(1, k+1):
        ans1 = dp[i-1][j-1] + x
        ans2 = -float('inf')
        if j >= 2:
            ans2 = dp[i-1][j-2]
        ans3 = one_direction(a, j)
        dp[i][j] = max(ans1, ans2, ans3)
        # print(i, j, a)
        # print(ans1, ans2, ans3)
        # print(dp)
print(dp[n][k])

Submission status: Accepted

Solution code:
import heapq
import copy

N, K = map(int, input().split())
V = list(map(int, input().split()))
max_sum = 0
for a in range(0, min(K+1, N+1)):
    for b in range(0, min(K+1-a, N+1-a)):
        sum_list=copy.copy(V[:a]+V[N-b:])
        heapq.heapify(sum_list)
        for i in range(K-a-b):
            if sum_list:
                q=heapq.heappop(sum_list)
                if q>0:
                    heapq.heappush(sum_list, q)
                    break
            else:
                break
        # print(a, b,K-a-b,V[:a]+V[N-b:], sum_list, sum(sum_list))
        # print(a, b,K-a-b)
        max_sum = max(max_sum, sum(sum_list))
print(max_sum)

Submission status: Accepted

Solution code:
#12:10
n,k = map(int,input().split())
v = list(map(int,input().split()))
can = []
for i in range(n+1):
  if i == 0:
    a = []
  elif i > k:
    break
  else:
    a.append(v[i-1])
  for j in range(n+1):
    if j == 0:
      b = []
    elif i + j > n or i + j > k:
      break
    else:
      b.append(v[-j])
    c = a + b
    c.sort()
    rest = min(k-i-j,len(c))
    tmp = sum(c)
    for de in range(rest):
      if c[de] < 0:
        tmp -= c[de]
      else:
        break
    can.append(tmp)
    #print(i,j,a,b,tmp)
print(max(can))

Submission status: Accepted

Solution code:
import unittest


class TestD(unittest.TestCase):
    def test_1(self):
        self.assertEqual(think(4, [-10, 8, 2, 1, 2, 6]), 14)

    def test_2(self):
        self.assertEqual(think(4, [-6, -100, 50, -2, -5, -3]), 44)

    def test_3(self):
        self.assertEqual(think(3, [-6, -100, 50, -2, -5, -3]), 0)


def solve():
    k, v = read()
    result = think(k, v)
    write(result)


def read():
    n, k = read_int(2)
    return k, read_int(n)


def read_int(n):
    return read_type(int, n)


def read_float(n):
    return read_type(float, n)


def read_type(t, n):
    return list(map(lambda x: t(x), read_line().split(' ')))[:n]


def read_line(n=0):
    if n == 0:
        return input().rstrip()
    else:
        return input().rstrip()[:n]


def think(k, v):
    max_value = -(10 ** 10)

    max_dequeue = min(len(v), k)
    for dequeue in range(max_dequeue + 1):
        max_enqueue = min(k - dequeue, dequeue)
        for left in range(dequeue + 1):
            dequeued_v = []
            right = dequeue - left
            dequeued_v += v[0:left]
            dequeued_v += [] if right == 0 else v[-right:]
            dequeued_v.sort()
            for i in range(max_enqueue + 1):
                max_value = max(max_value, sum(dequeued_v[i:]))
    return max_value


def write(result):
    print(result)


if __name__ == '__main__':
    # unittest.main()
    solve()

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines


# rstrip().decode('utf-8')
# INF=float("inf")
#MOD=10**9+7
# sys.setrecursionlimit(2147483647)
# import math
#import numpy as np
# import operator
# import bisect
# from heapq import heapify,heappop,heappush
#from math import gcd
# from fractions import gcd
# from collections import deque
# from collections import defaultdict
# from collections import Counter
from itertools import accumulate
# from itertools import groupby
# from itertools import permutations
# from itertools import combinations
# from scipy.sparse import csr_matrix
# from scipy.sparse.csgraph import floyd_warshall
# from scipy.sparse.csgraph import csgraph_from_dense
# from scipy.sparse.csgraph import dijkstra
# map(int,input().split())


def main():
	n,k=map(int,input().split())
	V=list(map(int,input().split()))
	V=[0]+V+[0]
	LL=list(accumulate(V))
	RR=list(accumulate(V[::-1]))[::-1]
	ans=0
	for l in range(n+1):
		for r in range(n-l+1):
			for x in range(l+r+1):
				if l+r+x<=k:
					xx=V[1:l+1]+V[n+1-r:n+1]
					xx.sort()
					xxx=list(accumulate(xx))
					xxx=[0]+xxx
					ans=max(ans,LL[l]+RR[n-r+1]-xxx[x])
	print(ans)

if __name__ == "__main__":
		main()

Submission status: Accepted

Solution code:
import heapq

N, KK = map(int, input().split())
V = list(map(int, input().split()))
ans = 0

for K in range(KK+1):
	for d in range(K):
		p = K-d
		if not(d < p <= N):
			continue	
		for l in range(p+1):
			r = p-l
			q = []
			for i in range(l):
				heapq.heappush(q,V[i])
			for i in range(r):
				heapq.heappush(q,V[-(i+1)])
			for i in range(d):
				heapq.heappop(q)
			ans = max(ans, sum(q))

print(ans)

Submission status: Accepted

Solution code:
import copy
n,k=map(int,input().split())
l=list(map(int,input().split()))
lr=[[0,[]]]
ll=[[0,[]]]
sumr,suml=0,0
lrr=[]
llr=[]
for i in range(n):
  suml+=l[i]
  sumr+=l[-1-i]
  if l[i]<0:
    llr.append(l[i])
  if l[-1-i]<0:
    lrr.append(l[-1-i])
  llr1=copy.deepcopy(llr)
  lrr1=copy.deepcopy(lrr)
  lr.append([sumr,lrr1])
  ll.append([suml,llr1])
max=-10**10
for i in range(n+1):
  for j in range(n+1):#左からi個右からj個
    if i+j>n or i+j>k:
      pass
    else:
      max1=lr[j][0]+ll[i][0]
      num=k-i-j
      list1=lr[j][1]+ll[i][1]
      list1=sorted(list1)
      for o in range(min(len(list1),num)):
        max1-=list1[o]
        if max1>max:
          max=max1
      if max1>max:
        max=max1
print(max)

Submission status: Accepted

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

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

        diff = K - left - right
        takes = V[:left] + V[N - right:]
        takes.sort(reverse=True)

        while diff > 0 and takes and takes[-1] < 0:
            takes.pop()
            diff -= 1

        ans = max(ans, sum(takes))

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 i in range(n+1):
    for j in range(n+1):
        if i + j > n or i + j > k:
            continue
        a = v[:i] + v[n - j:]
        a.sort()

        l = 0
        while True:
            if l == i + j or a[l] >= 0 or i+j+l == k:
                break
            l += 1
        b = a[l:]
        ans = max(ans, sum(b))
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
N,K=map(int,input().split())
V=list(map(int,input().split()))

left=[0]
right=[0]

for n in range(N):
    left.append(V[n]+left[n])
for n in range(N):
    right.append(V[-n-1]+right[n])

#print(left)
#print(right)

dp=[[0]*(K+1) for _ in range(K+1)]

for l in range(min(K+1,N+1)):
    for r in range(min(K-l+1,N-l+1)):
        dp[l][r]=left[l]+right[r]
        if N>l+r:
            temp=V[:l]+V[::-1][:r]#ここが不味い
        else:
            temp=V[:]
        #print(V,l,r,temp)
        temp.sort()
        
        #for i in range(min(K-l-r,N-l-r)):
        for i in range(K-l-r):
            #ここでマイナス項を引きたい
            if len(temp)==0 or temp[0]>=0:
                break
            else:
                e=temp.pop(0)
                #print(e)
                dp[l][r]-=e
                
ans=0
for item in dp:
    for obj in item:
        ans=max(ans,obj)
#print(dp)
print(ans)

Submission status: Accepted

Solution code:
# 2019-11-13 21:06:16(JST)
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# from scipy.misc import comb # float
# import numpy as np 

def main():
    n, k, *v = [int(x) for x in sys.stdin.read().split()]

    ma = 0
    for a in range(min(n, k)+1):
        for b in range(min(n, k)-a+1):
            take = v[:a] + v[-b:] if b != 0 else v[:a]
            take.sort()
            
            if a + b == 0:
                optimum_sum = 0
            else:
                for i in range(min(k-(a+b), a+b)-1, -1, -1):
                    if take[i] > 0:
                        continue
                    else:
                        optimum_sum = sum(take[i+1:])
                        break
                else:
                    optimum_sum = sum(take)
        
            ma = max(ma, optimum_sum)
    
    print(ma)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# 2019-11-13 21:06:16(JST)
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# from scipy.misc import comb # float
# import numpy as np 

def main():
    n, k, *v = [int(x) for x in sys.stdin.read().split()]

    ma = 0
    for a in range(min(n, k)+1):
        for b in range(min(n, k)-a+1):
            take = v[:a] + v[-b:] if b != 0 else v[:a]
            take.sort()
            
            if a + b == 0:
                optimum_sum = 0
            else:
                if k - (a + b) >= a + b:
                    for i in range(a+b-1, -1, -1):
                        if take[i] > 0:
                            continue
                        else:
                            optimum_sum = sum(take[i+1:])
                            break
                    else:
                        optimum_sum = sum(take)
                else:
                    for i in range(k-(a+b)-1, -1, -1):
                        if take[i] > 0:
                            continue
                        else:
                            optimum_sum = sum(take[i+1:])
                            break
                    else:
                        optimum_sum = sum(take)
            
            ma = max(ma, optimum_sum)
    
    print(ma)

if __name__ == "__main__":
    main()

Submission status: Accepted

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


# 操作の回数 n を a, b, cd の３つに分割する
def f(n):
    a = []
    for i in range(n+1):
        for j in range(i, n+1):
            a.append((i, j-i, n-j))
    return(a)


def main():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    ans = 0
    for a, b, cd in f(K):
        H = []
        D = collections.deque(V)
        for i in range(a):
            if not D:
                break
            heapq.heappush(H, D.popleft())
        for i in range(b):
            if not D:
                break
            heapq.heappush(H, D.pop())
        for i in range(cd):
            if not H or H[0] >= 0:
                break
            heapq.heappop(H)
        ans = max(ans, sum(H))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

ans = 0
for a in range(k+1):
    suba = vl[:a]
    for b in range(min(n+1-a, k+1-a)):
        subb = vl[-b:]
        if b == 0:
            subb = []
        sub = suba + subb
        ssub = sorted(sub)
        for _ in range(k-a-b):
            if len(ssub) == 0:
                break
            if ssub[0] < 0:
                ssub.pop(0)
            else:
                break
        if sum(ssub) > ans:
            ans = sum(ssub)

print(ans)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
arr = list(map(int,input().split()))
_max = min(N,K)
val_arr = []
for R in range(_max+1):
  max_L = _max-R
  for L in range(max_L+1):
    hand = arr[:R]
    max_D = K-R-L
    if L!=0:
      hand.extend(arr[-L:])
    hand = sorted(hand)
    
    #print(hand)
    n_num = len([h for h in hand if h < 0])
    D = min(max_D,n_num)
    value = sum(hand[D:])
    val_arr.append(value)
    
print(max(val_arr))

Submission status: Accepted

Solution code:
from bisect import bisect_left


def p_d():
    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):
            if _l + _r > n:
                break
            d = k - (_l + _r)
            s = v[:_l] + v[n - _r:]
            s.sort()
            d = min(len(s), d)
            ans = max(ans, sum(s[bisect_left(s, 0, 0, d):]))

    print(ans)
    
p_d()

Submission status: Accepted

Solution code:
from collections import deque

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

for a in range(min(K,N)+1):
  for b in range(min(K-a+1,N-a+1)):
    hou = []
    Vd = deque(V)
    for _ in range(a):
      hou.append(Vd.popleft())
    for _ in range(b):
      hou.append(Vd.pop())
    hou.sort()
    for _ in range(K-a-b):
      if hou:
        if hou[0]>0:
          break
        hou.pop(0)
    score = max(score,sum(hou))
    
print(score)

Submission status: Accepted

Solution code:
import copy
import heapq

tmp = list(map(int, input().split()))
n = tmp[0]
k = tmp[1]
v = list(map(int, input().split()))

a = [[0] * (k+1) for i in range(n+1)]
b = [[0] * (k+1) for i in range(n+1)]
ha = []
hb = []
for i in range(1, n+1):
  a[i][0] = a[i-1][0] + v[i-1]
  b[i][0] = b[i-1][0] + v[n-i]
  if v[i-1] < 0:
    heapq.heappush(ha, v[i-1])
  if v[n-i] < 0:
    heapq.heappush(hb, v[n-i])
  cha = copy.deepcopy(ha)
  chb = copy.deepcopy(hb)
  for j in range(1, k+1):
    if len(cha) != 0:
      a[i][j] = a[i][j-1] - heapq.heappop(cha)
    else:
      a[i][j] = a[i][j-1]
  for j in range(1, k+1):
    if len(chb) != 0:
      b[i][j] = b[i][j-1] - heapq.heappop(chb)
    else:
      b[i][j] = b[i][j-1]

maxv = 0
for i in range(0, k+1):
  for j in range(0,min(n+1, i+1)):
    for l in range(0,min(n+1, k-i+1)):
      tmp = a[j][i-j] + b[l][k-i-l]
      if (j+l) <= n and tmp > maxv:
        maxv = tmp
print (maxv)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda :sys.stdin.readline().rstrip()
def resolve():
    n,k=map(int,input().split())
    V=list(map(int,input().split()))

    from itertools import product
    import heapq
    score=0
    # l,r : 左、右から取り出す個数
    for l,r in product(range(0,k+1),repeat=2):
        if(l+r>k or l+r>n): continue
        A=[]
        for i in range(l):
            heapq.heappush(A,V[i])
        for i in range(n-r,n):
            heapq.heappush(A,V[i])
        for _ in range(k-l-r):
            if(A):
                a=heapq.heappop(A)
                if(a>0):
                    heapq.heappush(A,a)
        score=max(score,sum(A))
    print(score)
resolve()

Submission status: Accepted

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

ans = -1
for i in range(min(N + 1, K + 1)): #i個ゲット
    for l in range(i + 1): #左からいくつのindexまでとるか
        a = V[0:l] + V[N - (i - l):N]
        a.sort()

        # K- i 個負のvalueを捨てれる
        t = 0
        s = sum(a)
        while i > t and K - i > t:
            if a[t] >= 0:
                break
            s -= a[t] #負の減算なので加算
            t += 1
        ans = max(ans, s)

print(ans)