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:
def MAP(): return map(int,input().split())

n,k = MAP()
*v, = MAP()

operation = min(n,k) #取り出すMAX回数
ans=0

for i in range(1,operation+1):
    for j in range(i+1):
        A = j   #左側から取り出す回数
        B = i-j    #右側から取り出す回数
        t = v[:A]
        if B>0:
            t+=v[-B:]
        t.sort()

        l = min(k-i,i-1)
        for ll in range(l):
            if t[ll] >= 0:
                l = ll
                break
        s = sum(t[l:])
        ans = max(ans,s)

print(ans)

Submission status: Accepted

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

m=min(n,ki)
ans=0

for i in range(m+1):
    for j in range(i+1):
        q=[]
        tmp=0
        for k in range(j):
            if len(v)>0:
                q.append(v[k])
        for kz in range(i-j):
            if len(v)>0:
                q.append(v[n-1-kz])
        tmp=sum(q)
        q.sort()
        for l in range(ki-i):
            if l<len(q) and q[l]<0:
                tmp-=q[l]
        ans=max(ans,tmp)
        
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
lst = list(map(int, input().split()))
ans = 0
for l in range(K+1):
    for r in range(K+1-l):
        if l + r > N:
            break
        get = lst[:l]
        get.extend(lst[N-r:])
        cnt = sum(get)
        get.sort()
        for i in range(min(K-l-r, l+r)):
            if get[i] >= 0:
                break
            cnt -= get[i]
        ans = max(ans, cnt)
print(ans)

Submission status: Accepted

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

from collections import deque
from heapq import heappush, heappop

res = 0

for i in range(0, min(k, n) + 1):
    for j in range(i + 1):
        a = j
        b = i - j

        hq = []
        dq = deque(vs)

        for _ in range(a):
            heappush(hq, dq.popleft())
        for _ in range(b):
            heappush(hq, dq.pop())

        c = k - a - b
        for _ in range(c):
            if len(hq) == 0:
                break
            v = heappop(hq)
            if v > 0:
                heappush(hq, v)
                break

        res = max(res, sum(hq))

print(res)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop
N, K = map(int, input().split())
V = list(map(int, input().split()))

ans = 0
mi = min(N, K)

for l in range(mi+1):
    for r in range(mi-l+1):
        heap = []
        for x in V[:l]:
            heappush(heap, x)
        for x in V[N-r:]:
            heappush(heap, x)
        
        cnt = l + r
        while (len(heap) > 0) & (cnt < K):
            x = heappop(heap)
            if x > 0:
                heappush(heap, x)
                break
            cnt += 1
        
        ans = max(ans, sum(heap))
    
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
import bisect
from operator import itemgetter
import math
import functools
import itertools
import numpy as np
import sys
MAX_INT = int(10e10)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

N,K = IL()
v = IL()

VList = [[] for _ in range(N+1)]

ans = 0
for left in range(N+1):
  for right in range(N+1):
    if left+right == 0:
      continue
    if left+right > min(N, K):
      break
    else:
      l = v[:left] + v[N-right:]
      cnt = K - (left+right)
      l.sort()
      tmp = sum(l)
      for j in range(min(cnt, len(l))):
        if l[j] < 0:
          tmp -= l[j]
        else:
          break
      ans = max(ans, tmp)

print(ans)

Submission status: Accepted

Solution code:
"D equeue"
N, K = map(int, input().split())  # N個の宝石, K回数の操作
V = list(map(int, input().split()))

max_value = 0
for a in range(K+1):
    for b in range(K+1):
        gain_tresure = []
        if (a + b) > min(K, N):
            continue
        gain_tresure.extend(V[:a])
        gain_tresure.extend(V[N-b:])
        # print("------------------")
        # print(gain_tresure)
        # print(K-(a+b))
        # print("------------------")
        gain_tresure = sorted(gain_tresure)
        for i in range(min(K-(a+b), len(gain_tresure))):
            if gain_tresure[i] < 0:
                gain_tresure[i] = 0
        max_value = max(max_value, sum(gain_tresure))

print(max_value)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
a=list(map(int,input().split()))
g=0
for i in range(0,min(n,k)+1):
    for j in range(0,min(k-i,n-i)+1):
        s=sorted(a[:i]+a[n-j:])
        p=sum(s)
        t=i+j
        c=0
        while len(s)>=c+1 and t+1<=k:
            if s[c]<0:
                p-=s[c]
                c+=1
                t+=1
            else:
                break
        g=max(g,p)
print(g)

Submission status: Accepted

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

ans = 0
for i in range(min(N,K)+1):
  for j in range(min(N,K)-i+1):
    if j == 0:
      Selected = V[:i]
    else:
      Selected = V[:i] + V[-j:]
    count = K - i - j
    #print(i,j,Selected,count)
    Selected.sort()
    for k in range(min(len(Selected),count)):
      if Selected[k] < 0:
        Selected[k] = 0
    ans = max(ans,sum(Selected))
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
v = [int(e) for e in input().split()]
m = min(n, k)
result = 0
for i in range(m + 1):
  for j in range(i + 1):
    t = v[:j]
    t.extend(v[n - (i - j):])
    t.sort()
    l = k - i
    while len(t) > 0 and l > 0 and t[0] < 0:
      t.pop(0)
      l -= 1
    m = sum(t)
    if m > result:
      result = m
print(result)

Submission status: Accepted

Solution code:
def main():
    N, K = map(int, input().split())
    V = [int(v) for v in input().split()]
    pre = [[]]
    prefix_sum = [0]
    for v in V:
        prefix_sum.append(prefix_sum[-1] + v)
        if v < 0: pre.append(pre[-1] + [v])
        else: pre.append(pre[-1])

    post = [[]]
    suffix_sum = [0]
    for v in V[::-1]:
        suffix_sum.append(suffix_sum[-1] + v)
        if v < 0: post.append(post[-1] + [v])
        else: post.append(post[-1])
    # print(prefix_sum, suffix_sum)
    # print(V)
    max_tot = 0
    for i in range(min(K, N)+1):
        for j in range(min(K, N)-i+1):
            tot = prefix_sum[i] + suffix_sum[j]
            # print(i, j, tot)
            # print(pre[i], post[i])
            if K > i+j:
                d = K-i-j
                neg = sorted(pre[i] + post[j])
                tot -= sum(neg[:d])
            max_tot = max(max_tot, tot)
    return max_tot


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

Submission status: Accepted

Solution code:
from collections import deque

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

ans = 0
for t in range(k//2 + 1):
    hand = deque(V[:k-t])
    rest = deque(V[k-t:])
    cur_sum = sum(hand)

    for j in range(k-t+1):
        put_back = 0
        rev_hand = sorted(hand)

        for i in range(t):
            jewel = rev_hand[i]
            if jewel < 0:
                put_back -= jewel
            else:
                break

        candidate = cur_sum + put_back
        ans = max(candidate, ans)

        to_rest = hand.pop()
        rest.appendleft(to_rest)
        to_hand = rest.pop()
        hand.appendleft(to_hand)

        cur_sum += to_hand - to_rest

print(ans)

Submission status: Accepted

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

ans = 0
for l in range(n+1):
    for r in range(l,max(n,l+1)):
        m = v[:l]+v[r+1:]
        if len(m) > k:
            continue
        m.sort()
        i=0
        while i < len(m) and i < k - len(m) and m[i] < 0:
            i+=1
        ans = max(ans,sum(m[i:]))
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
def main():
    n,k = map(int,input().split())
    ls = [int(x) for x in input().split()]
    ans = 0
    for i in range(min(k,n)+1):
        for j in range((min(k,n)+1)-i):
            now = ls[:i] + ls[n-j:] + [0]
            now = sorted(now)
            can = sum(now)
            now = deque(now)
            roop = 0
            while 1:
                if  roop == k-(i+j):
                    break
                pop = now.popleft()
                if pop>=0:
                    break
                else:
                    can -= pop
                roop += 1
            ans = max(can,ans)
    print(ans)
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
def main():
    n,k = map(int,input().split())
    ls = [int(x) for x in input().split()]
    ls_r = [0]*(n+1)
    for i in range(n):
        ls_r[i+1] = ls_r[i]+ls[i]
    ls_l = [0]*(n+1)
    for i in range(n):
        ls_l[i+1] = ls_l[i]+ls[i]

    ans = 0
    for i in range(min(k,n)+1):
        for j in range((min(k,n)+1)-i):
            now = ls[:i] + ls[n-j:] + [0]
            now = sorted(now)
            can = sum(now)
            now = deque(now)
            roop = 0
            while 1:
                if  roop == k-(i+j):
                    break
                
                pop = now.popleft()
                if pop>=0:
                    break
                else:
                    can -= pop
                roop += 1
            ans = max(can,ans)
    print(ans)



if __name__ == "__main__":
    main()

Submission status: Accepted

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

import heapq
import copy
def main(): 
    N,K = map(int,input().split())
    v=list(map(int, input().split()))
    l_count = []
    heapq.heapify(l_count)
    ans = 0
    for l in range(N+1):
        if l!=0: heapq.heappush(l_count,v[l-1])
        r_count = copy.deepcopy(l_count)
        for r in range(N-l+1):
            if r!=0: heapq.heappush(r_count,v[N-r])
            d_count = copy.deepcopy(r_count)
            for d in range(K-l-r+1):
                if not(len(d_count) == 0 or d==0):
                    heapq.heappop(d_count)
                sum_d_count = sum(d_count)
                if sum_d_count > ans:
                    ans = sum_d_count
    print(ans)
            
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for k in range(K+1):
    for n in range(k+1):
        if n >= N or k > N:
            break
        A = V[:n]
        A.extend(V[N-k+n:])
        A.sort()
        
        c = sum(A)
        for i in range(min(K-k, k)):
            if A[i] <= 0:
                c -= A[i]
        #print(k, n, c)
        ans = max(ans, c)
print(ans)

Submission status: Accepted

Solution code:
n, k = list(map(int, input().split()))
Gem = list(map(int, input().split()))
gem = []
Max = Gem[0]
r = min(n,k)
for i in range(r + 1):
    gem = []
    for j in range(r - i + 1):
        gem = Gem[0:i]
        gem += Gem[n - j:n]
        dif = k - (i + j)
        for s in range(dif):
            if len(gem) == 0:
                break
            M = gem.index(min(gem))
            if gem[M] < 0:
                del gem[M]
            else:
                break
        if len(gem) == 0:
            Max = max(Max,0)
        elif Max < sum(gem):
            Max = sum(gem)
print(Max)

Submission status: Accepted

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

items = []
ans = 0
for l in range(K+1):
    for m in range(K - l + 1):
        if l + m > N: break
        litems = deque[0:l]
        mitems = deque[N-m:]
        arr = litems + mitems
        arr.sort()
        items.append(arr)

        d = K - l - m
        for n in range(min(len(arr), d+1)):
            ans = max(ans, sum(arr[n:]))

print(ans)

Submission status: Accepted

Solution code:
def main():
    import collections
    import copy
    N,K = map(int, input().split())
    V = collections.deque(map(int, input().split()))

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


    for i in range(1,K+1):
        for j in range(max(1,i//2),min(i+1,N+1)):
            opt = 0
            for k in range(j+1):
                tmp = copy.deepcopy(V)
                tmp2 = collections.deque()
                for _ in range(k):
                    tmp2.append(tmp.popleft())
                for _ in range(j-k):
                    tmp2.append(tmp.pop())
                tmp2 = list(tmp2)
                tmp2.sort()
                for l in range(min(i-j,j)):
                    if tmp2[l] < 0:
                        tmp2[l] = 0
                S = sum(tmp2)
                if S > opt:
                    opt = S
            answer[i][j] = opt
    Ans = 0
    for i in range(K+1):
        for j in range(K+1):
            if answer[i][j] > Ans:
                Ans = answer[i][j]
    print(Ans)

main()

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heapify
N, K = map(int, input().split())
V = [int(i) for i in input().split()]
ans = 0

for i in range(min(K,N)+1):
  for l in range(i+1):
    H = []
    r = i-l
#    print(i,l,r)
    H.extend(V[:l])
    if r > 0:
      H.extend(V[-r:])
    heapify(H)
    for j in range(min(K-i,i)):
      if H[0] >= 0:
        break
      heappop(H)
    ans = max(ans,sum(H))
#  print(H)
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
Q = list(map(int, input().split()))
dp = [0 for _ in range(K + 1)]
for i in range(min(K + 1, N + 1)):
  for j in range(i + 1):
    if i != j:
      q = sorted(Q[: j] + Q[-(i - j): ], reverse = True)
    else:
      if i == 0:
        continue
      q = sorted(Q[: j], reverse = True)
    #print(i, j, q)
    k = 0
    while k < K - i:
      if len(q) == 0:
        break
      if q[-1] < 0:
        k += 1
        q.pop()
      else:
        break
    dp[i] = max(sum(q), dp[i])
#print(dp)
print(max(max(dp), 0))

Submission status: Accepted

Solution code:
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-i): # 右端から取り出す回数
        L = V[:i]
        if j == 0:
            R = []
        else:
            R = V[-j:]
        LR = L + R
        if len(LR) > K:
            continue
        num_drop = min(len(LR), K-i-j)
        LR.sort()
        total = sum(LR)
        idx = 0
        while idx < num_drop:
            if LR[idx] < 0:
                total -= LR[idx]
                idx += 1
            else:
                break
        ans = max(ans, total)


print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
lst = list(map(int, input().split()))
res = []
for i in range(min(k, len(lst))):
  throwaways = i
  take = min(k - throwaways, len(lst))
  # throwaways cannot be larger than take
  if throwaways > take:
    break
  for j in range(take+1):
    right = lst[:j]
    if len(right) < take:
      l = take - len(right)
      left = lst[l*-1:]
    else:
      left = []
    m_lst = sorted(right + left)
    for t in range(throwaways):
      # throw away if it's value is negative
      if m_lst[0] < 0:
        del m_lst[0]
    res.append(m_lst)
max_num = max([sum(e) for e in res])
if max_num <= 0:
  print(0)
else:
  print(max_num)

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(K+1):
        if i+j>K or i+j>N:
            continue
        tmp=V[:i]+V[N-j:]
        tmp.sort()
        count_tmp=0
        ans_tmp=sum(tmp)
        for k in tmp:
            if k < 0 and count_tmp < K-i-j:
                ans_tmp-=k
                count_tmp+=1
            ans=max(ans,ans_tmp)
print(ans)

Submission status: Accepted

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


ans = 0
for k1 in range(k+1):
    for k2 in range(k+1):
        if k1 + k2 > k or k1 + k2 > n or k1 > n or k2 > n:
            continue

        w = v[:k1] + v[n-k2:]
        w.sort()
        ans = max(ans, sum(w))
        # print(k1, k2, max(0, k-k1-k2), len(w), w)
        for k3 in range(1, max(0, k-k1-k2)+1):
            ans = max(ans, sum(w[k3:]))

print(ans)

Submission status: Accepted

Solution code:
from collections import deque
from heapq import heapify, heappush, heappop
from copy import deepcopy
N, K = map(int, input().split())
D = deque(map(int, input().split()))
ans = 0

for r in range(1, min(N, K)+1):
    for a in range(0, r+1):
        total = 0
        V = deepcopy(D)
        bag = []
        heapify(bag)
        minus = 0
        b = r-a
        for i in range(a):
            stone = V.popleft()
            total += stone
            heappush(bag, stone)
            if stone < 0:
                minus += 1
        for i in range(b):
            stone = V.pop()
            total += stone
            heappush(bag, stone)
            if stone < 0:
                minus += 1
        for i in range(minus):
            if i == (K-r):
                break
            total -= heappop(bag)
        ans = max(total, ans)

print(ans)

Submission status: Accepted

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

ans = 0
m = min(n,k)
for a in range(m+1):
    for b in range(m+1-a):
        jewel = lst[:a] + lst[n-b:]
        jewel.sort()
        for c in range(k+1-a-b):
            ans = max(ans, sum(jewel[c:]))
        
print(ans)

Submission status: Accepted

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

res = 0
max_num = min(n, k)
for i in range(max_num+1):
    for j in range(max_num+1 - i):
        my_lst = []
        my_lst += lst[:i]
        if j != 0:
            my_lst += lst[-j:]
        
        s = sum(my_lst)
        sorted_my_lst = sorted(my_lst)
        #print('my_lst :', my_lst)
        for l in range(k- i - j):
            if len(my_lst) > l:
                if sorted_my_lst[l] < 0:
                    s -= sorted_my_lst[l]
        res = max(res, s)

print(res)

Submission status: Accepted

Solution code:
from collections import deque 

n, k = map(int, input().split())
vs_ = deque(map(int, input().split()))

max_v = 0

import copy

for a in range(k+1):
  for b in range(k+1-a):
    for c in range(k+1-a-b):
      vs = copy.copy(vs_)
      us = []
      for x in range(a):
        if vs:
          us.append(vs.popleft())
        else:
          break
      for y in range(b):
        if vs:
          us.append(vs.pop())
        else:
          break
      #print(us)
      us.sort(reverse=True)
      for z in range(c):
        if len(us) and us[-1]<0:
          us.pop()
        else:
          break
      if sum(us) >= max_v:
        max_v = sum(us)

print(max_v)

Submission status: Accepted

Solution code:
#デックをインポート
from collections import deque

#前準備
n,k=[int(i) for i in input().split()]

#デックを用意
D=deque()
h=[int(i) for i in input().split()]
for i in h:
    D.append(i)   
    
#答え
maxnum=0

#繰り返す単位
times=min(n,k)

#aとbの操作の合計のlimitを設定
for limit in range(times+1):
#     print(D)
    
    #aの操作を決定
    for a in range(limit+1):
        get=[]
        Dcopy=deque()
        for i in range(n):
            Dcopy.append(D[i])
        b=limit-a
        for i in range(a):
            get.append(Dcopy.popleft())
        for i in range(b):
            get.append(Dcopy.pop())
        get.sort(reverse=True)
#         print(get)
        for i in range(k-limit):
            if len(get)==0:
                break
            if get[-1]>=0:
                break
            get.pop()
        sumnum=0
        for i in get:
            sumnum+=i
        if sumnum>maxnum:
            maxnum=sumnum
            
#         print(a,b,Dcopy,get,sumnum)
print(maxnum)

Submission status: Accepted

Solution code:
from bisect import insort_right as ir

N, K = list(map(int, input().split()))
V = list(map(int, input().split()))
ans = [0]

def right(x, k, l, lim):
    if lim > k:
        lim = k
    for vr in V[::-1][:lim]:
        k -= 1
        ir(l, vr)
        if vr <= 0:
            x += 1
        ans.append(sum(l[min(k, x):]))    

x1, k1, l1, lim1 = 0, K, [], N
if lim1 > K:
    lim1 = K
right(0, K, [], N - 1)
for vl in V[:lim1]:
    k1 -= 1
    ir(l1, vl)
    if vl <= 0:
        x1 += 1
    ans.append(sum(l1[min(k1, x1):]))
    x2, k2, l2, lim2 = x1, k1, l1[:], N + k1 - K
    right(x2, k2, l2, lim2)
ans.append(sum(l1[min(k1, x1):]))
print(max(ans))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
v = [int(e) for e in input().split()]
m = min(n, k)
result = 0
for i in range(m + 1):
  for j in range(i + 1):
    t = v[:j]
    t.extend(v[n - (i - j):])
    t.sort()
    l = k - i
    while len(t) > 0 and l > 0 and t[0] < 0:
      t = t[1:]
      l -= 1
    m = sum(t)
    if m > result:
      result = m
print(result)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
r = min(n,k)
get = []
M = 0
for i in range(r+1):
  for j in range(i+1):
    get += v[0:j] + v[(n-i+j):n]
    get.sort()
    R = min(i,k-i)
    for cd in range(0,R+1):
      M = max(M,sum(get[cd:i]))
    get = []
print(M)

Submission status: Accepted

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

res=[]
for x in range(min(n,k)+1):
	for a in range(x+1):
		b=x-a
		l=v[:a]
		r=v[n-b:]
		z=[]
		for t in l:
			if t<0:
				z.append(-t)
		for t in r:
			if t<0:
				z.append(-t)
		z.sort()
		z=z[::-1]
		res.append(sum(l)+sum(r)+sum(z[:k-x]))
		#print(l,r,z)
print(max(res))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
v=list(map(int,input().split()))
lim=min(n,k)
V=len(v)
ans=-1*float("inf")
for a in range(0,lim+1):
    for b in range(0,lim+1):
        x=[]
        m=k-a-b
        if a+b>lim:
            break
        for i in range(a):
            x.append(v[i])
        for i in range(V-1,V-b-1,-1):
            x.append(v[i])
        x.sort()
        for i in range(m):
            if x:
                if x[0]<0:
                    X=x.pop(0)
        ans=max(ans,sum(x))
print(ans)

Submission status: Accepted

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

ans = []
for i in range(min(N,K)+1):
  for j in range(min(N,K)+1-i):
    Vc = deque(V.copy())
    cal = deque([0])
    for k in range(i):
      cal.append(Vc.popleft())
    for l in range(j):
      cal.append(Vc.pop())
    cal = deque(sorted(cal))
    for m in range(K-i-j):
      if cal[0] < 0:
        cal.popleft()
      else:
        break
    ans.append(sum(cal))

print(max(ans))

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
*V, = map(int, input().split())
M = [v if v < 0 else 0 for v in V]
S = [0]
for i in range(1, min(k+1, n+1)):
    for j in range(i+1):
        s = sum(V[:i-j])+sum(V[n-j:])
        M_sub = sorted(M[:i-j]+M[n-j:])
        s -= sum(M_sub[:k-i])
        S += [s]
print(max(S))

Submission status: Accepted

Solution code:
import os,re,sys,operator
from collections import Counter,deque
from operator import itemgetter
from itertools import accumulate,combinations,groupby
from sys import stdin,setrecursionlimit
from copy import deepcopy
import heapq

setrecursionlimit(10**6)

n,k=map(int,stdin.readline().rstrip().split())
v=deque([int(i) for i in stdin.readline().rstrip().split()])
ans=0
m=min(n,k)+1
loop=iter((i,j) for i in range(m) for j in range(m-i))
for i in loop:
    now=[]
    heapq.heapify(now)
    aban=k-(i[0]+i[1])
    
    for j in range(i[0]):
        heapq.heappush(now,v[j])
    
    for j in reversed(range(n-1,n-i[1]-1,-1)):
        heapq.heappush(now,v[j])
    
    for j in range(aban):
        if len(now)!=0 and now[0]<0:
            heapq.heappop(now)
        else:
            break
    ans=max(sum(now),ans)
print(ans)

Submission status: Accepted

Solution code:
# ABC128D - equeue
# exhaustive search
def main():
    N, K = tuple(map(int, input().rstrip().split()))
    V = tuple(map(int, input().rstrip().split()))
    lim = min(N, K)
    ans = set()
    for l in range(N + 1):
        for r in range(N + 1):
            if l + r > lim:
                break
            # picked jewels (l from left, r from right)
            cur = sorted(V[:l] + V[-r:]) if r != 0 else sorted(V[:l])
            neg = sum(i < 0 for i in cur)
            rest = K - (l + r)
            # return unworthy ones as much as possible
            if neg > rest:
                ans |= {sum(cur[rest:])}
            else:
                ans |= {sum(i for i in cur if i >= 0)}
    print(max(ans))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:


def getint(): return int(input())
def getints(): return list(map(int, input().split()))

n,k = getints()
vs = getints()

res = 0
for take_operation in range(0, k + 1):
    sute_operation = k - take_operation
    if take_operation > n:
        continue
    for take_from_left in range(0, take_operation+1):
        take_from_right = take_operation - take_from_left
        item_values = []
        for i in range(0, take_from_left):
            item_values.append(vs[i])
        for i in range(0, take_from_right):
            item_values.append(vs[n - 1 - i])
        item_values = list(sorted(item_values, reverse=True))
        for i in range(sute_operation):
            if item_values and item_values[-1] < 0:
                item_values.pop()
        tmp = 0 if not item_values else sum(item_values)
        res = max(res, tmp)
print(res)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

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

ans = 0  # 何もしないと0なので、ansの初期値は0


for pick in range(min(n+1,k+1)):
    #  pick->取り出す操作をする回数(listより多く取り出さないように注意)

    for right in range(pick+1):
        left= pick-right # 左から取り出す数
        pick_list=v[:right]+v[n-left:]
        pick_list=sorted(pick_list)
        temp_ans=sum(pick_list)
        rem=min(k-pick,pick)# 右から取り出す数
        for i in range(rem):
            if pick_list[i]<0:
                temp_ans-=pick_list[i]
            else:
                break
        ans=max(ans,temp_ans)
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split(" "))
V = list(map(int, input().split(" ")))
V_rev = list(reversed(V))
val = [[0] * (N + 1) for _ in range(N + 1)]

for i in range(N):
    for j in range(N):
        val[i + 1][j] = val[i][j] + V[i]
        val[i][j + 1] = val[i][j] + V_rev[j]

val[N][N] = val[N][N - 1] + V_rev[N - 1]

ans = 0
for l in range(N + 1):
    for r in range(N + 1):
        num = l + r
        if num > K or num > N:
            continue
        rm = []
        can = (K - num)
        for li in range(l):
            if V[li] < 0:
                rm.append(V[li])
        for ri in range(r):
            if V_rev[ri] < 0:
                rm.append(V_rev[ri])

        rm.sort()
        ans = max(ans, val[l][r] - sum(rm[:can]))

print(ans)

Submission status: Accepted

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

ans = 0

for i in range(k+1):
    l = min(i,n)
    for j in range(l+1):
        left_gain = jewel_list[:j]
        if l-j != 0:
            right_gain = jewel_list[-l+j:]
        else:
            right_gain = []
        
        gabage = sorted(left_gain+right_gain)[:k-i]

        total = sum(left_gain+right_gain)
        for p in gabage:
            if p < 0:
                total -= p
            else:
                break
        ans = max(ans,total)

print(ans)

Submission status: Accepted

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

m=[]
M = min(n,k) +1
for i in range(M):
 for j in range(M-i):
  # print(i,j)
  t=sorted(v[:i]+v[:~j:-1])

  while t and(k-i-j)*t[0]<0:t.pop(0);j+=1
  m.append(sum(t))
print(max(m))

Submission status: Accepted

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

m=[]
for i in range(k+1):
 for j in range(min(k,n)-i+1):
  # print(i,j)
  t=sorted(v[:i]+v[:~j:-1])

  while t and(k-i-j)*t[0]<0:t.pop(0);j+=1
  m.append(sum(t))
print(max(m))

Submission status: Accepted

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

m=[]
for i in range(k+1):
 for j in range(min(k,n)-i+1):
  # print(i,j)
  t=sorted(v[:i]+v[:~j:-1])
  while t and(k-i-j)*t[0]<0:t.pop(0);j+=1
  m+=sum(t),
print(max(m))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import math


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

ans = 0
max_pop_cnt = min(n, k)
for pop_cnt in range(max_pop_cnt+1):
#  pop_cnt+1にしないと、pop_cntが0の場合は消えてしまう。
    for right in range(pop_cnt+1):
        for push_cnt in range((k - pop_cnt)+1):
            ans = max(ans, sum(sorted(que[:pop_cnt-right] + list(reversed(que))[:right])[push_cnt:]))
# reverseにした方がいい。-1で後ろからスライスをとると、0の場合に全部になってしまう。
print(ans)