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 main():
    n, k = map(int, input().split())
    v = [int(x) for x in input().split()]
    
    ans = 0
    r = min([n, k])
    for i in range(r+1):
        for j in range(r+1-i):
            sub = sum(v[:i])+sum(v[n-j:n])
            minus = []
            for l in range(n):
                if (l < i or n-j < l) and v[l] < 0:
                    minus.append(v[l])
            minus.sort()
            sub -= sum(minus[:min([len(minus), k-i-j])])
            if ans < sub:
                ans = sub
        
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import heapq
from collections import deque
import copy

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

    left_plus = 0
    left_minus_count = 0
    left_minus_list = []
    
    ans = 0
    sub = 0
    minus_list = []
    minus_count = 0
    heapq.heapify(minus_list)
    for i in range(n-1, max([-1, n-k-1]), -1):
        if v[i] >= 0:
            sub += v[i]
        else:
            heapq.heappush(minus_list, -v[i])
            minus_count += 1
        while n-i+minus_count > k and minus_list:
            sub -= heapq.heappop(minus_list)
            minus_count -= 1
        if n-i+minus_count > k:
            break
        if ans < sub:
            ans = sub
    
    for i in range(min([n, k])):
        if v[i] >= 0:
            left_plus += v[i]
        else:
            left_minus_list.append(-v[i])
            left_minus_count += 1
        
        sub = left_plus
        minus_count = left_minus_count
        minus_list = copy.deepcopy(left_minus_list)
        heapq.heapify(minus_list)
        while i+minus_count+1 > k and minus_list:
            minus_count -= 1
            sub -= heapq.heappop(minus_list)
        if i+minus_count+1 <= k and ans < sub:
            ans = sub
        sub = left_plus
        minus_count = left_minus_count
        minus_list = copy.deepcopy(left_minus_list)
        heapq.heapify(minus_list)
        for j in range(n-1, max([i, n-k+i+1]), -1):
            if v[j] >= 0:
                sub += v[j]
            else:
                minus_count += 1
                heapq.heappush(minus_list, -v[j])
            while minus_count+i+n-j+1 > k and minus_list:
                minus_count -= 1
                sub -= heapq.heappop(minus_list)
            
            if i+(n-j)+minus_count+1 > k:
                break
            if ans < sub:
                ans = sub
        
        
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    n,k = map(int,input().split())
    v = list(map(int,input().split()))
    m = 0
    for i in range(k+1):
        if i > n:
            rem = k-n
            have = v
            while len(have)>0 and have[0]<0 and rem>0:
                    have.pop(0)
                    rem -= 1
            s = sum(have)
            if m<s:
                m = s
            break
        for j in range(i+1):
            l=j
            r=i-l
            have = v[0:l]+v[n-r:n]
            rem = k-i
            have = sorted(have)
            if len(have)==0:
                s = 0
            else:
                while len(have)>0 and have[0]<0 and rem>0:
                    have.pop(0)
                    rem -= 1
                s = sum(have)
            if m<s:
                m = s
    print(m)

        

if __name__ == "__main__":
    main()

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): #i個の宝石を得る
    for a in range(i+1): #左からa個の宝石を得る
        b=i-a #右からb個の宝石を得る
        val=sorted(v[:a]+v[N-b:]) #宝石の価値の合計
        s=sum(val)
#        print(val)
        for j in range(0,min(K-i,len(val))): #j個の宝石を捨てる、上限はk-iか得た宝石の個数i
            if j<len(val):
#                print("#",a,b,min(K-i,len(val)),val)
                if val[j]<0: #負の宝石を捨てる
                    s-=val[j]
            else:
                break
#        print(a,b,min(K-i,len(val)),val,sum(val))
        ans=max(ans,s)
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
r = min(n,k)
ans = -10**10
for i in range(0,r+1):
  for a in range(i+1):
    b = i - a
    val = sorted(v[:a]+v[(n-b):])
    s = sum(val)
    for j in range(min(k-i,len(val))):
      if val[j] < 0:
        s -= val[j]
      else:
        break
    ans = max(ans,s)
print(ans)

Submission status: Accepted

Solution code:
def main():
    import sys
    import heapq
    from copy import deepcopy
    from collections import deque
    sys.setrecursionlimit(10 ** 6)
    input = sys.stdin.readline
    N, K = [int(x) for x in input().strip().split()]
    V = [int(x) for x in input().strip().split()]
    ans = -float('inf')
    for l in range(min(N, K)+1):
        for r in range(min(N, K)-l+1):
            vt = sorted(V[:l] + V[N-r:])
            c = 0
            i = 0
            for i in range(len(vt)):
                if c == (K-l-r):
                    break
                if vt[i] < 0:
                    vt[i] = 0
                    c += 1
                else:
                    break
            ans = max(ans, sum(vt))

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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


def solve(N: int, K: int, V: "List[int]"):

    sum_l = []
    for lk in range(min(N+1, K+1)):
        rk = min(N-lk, K - lk)
        if rk>0:
            q = V[:lk][::-1] + V[-rk:]
        else:
            q = V[:lk][::-1]
        
        m = 0
        sum_=0
        mn = K - (lk+rk)


        for i in range(len(q)):
            q_ = q[i:]
            m = i+mn
            q_s = sorted(q_)
            for x in range(len(q_s)):
                if (q_s[x]<0)&(m>0):
                    m-=1
                else:
                    break
            sum_ = sum(q_s[i+mn-m:])
            sum_l.append(sum_)

    
    print(max(sum_l))
    return


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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for A in range(min(N, K)+1):
    for B in range(min(N, K)+1-A):
        hand = V[:A]+V[N-B:]
        hand.sort()
        i = 0
        while i < K-A-B and i < len(hand) and hand[i] < 0:
            hand[i] = 0
            i += 1
        ans = max(ans, sum(hand))
print (ans)

Submission status: Accepted

Solution code:
def main():
    n,k=map(int,input().split())
    v=list(map(int,input().split()))
    ans=0
    for a in range(min(n,k)+1):
        for b in range(min(n,k)-a+1):
            chk=v[:a]+v[n-b:]
            chk.sort()
            x,s=0,sum(chk)
            while x<k-(a+b) and len(chk)>x:
                s-=min(0,chk[x])
                x+=1
            ans=max(ans,s)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, K = lr()
V = lr()
scores = set()
limit = min(N, K)
for i in range(limit+1): # iは左から取り出す個数
    for j in range(limit-i+1): # jは右から取り出す個数
        stone = V[:i] + V[N-j:]
        stone.sort()
        result = sum(stone)
        scores.add(result)
        for k in range(min(len(stone), K-(i+j))): # kは戻す個数
            if stone[k] >= 0:
                break
            result -= stone[k]
            scores.add(result)

answer = max(scores)
print(answer)
#

Submission status: Accepted

Solution code:
# coding: utf-8
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, K = lr()
V = lr()
answer = 0
limit = min(N, K)
for i in range(limit+1): # iは左から取り出す個数
    for j in range(limit-i+1): # jは右から取り出す個数
        stone = V[:i] + V[N-j:]
        stone.sort()
        result = sum(stone)
        if result > answer:
            answer = result
        for k in range(min(len(stone), K-(i+j))): # kは戻す個数
            if stone[k] > 0:
                break
            result -= stone[k] 
            if result > answer:
                answer = result

print(answer)
# 07

Submission status: Accepted

Solution code:
# coding: utf-8
import sys

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, K = lr()
V = lr()
scores = [0]
limit = min(N, K)
for i in range(limit+1): # iは左から取り出す個数
    for j in range(limit-i+1): # jは右から取り出す個数
        stone = V[:i] + V[N-j:]
        stone.sort()
        result = sum(stone)
        scores.append(result)
        for k in range(min(len(stone), K-(i+j))): # kは戻す個数
            if stone[k] > 0:
                break
            result -= stone[k] 
            scores.append(result)

answer = max(scores)
print(answer)
# 07

Submission status: Accepted

Solution code:
def main():
    n,k=map(int,input().split())
    v=list(map(int,input().split()))
    ans=0
    for a in range(min(n,k)+1):
        for b in range(min(n,k)-a+1):
            chk=v[:a]+v[n-b:]
            chk.sort()
            x,s=0,sum(chk)
            while x<k-(a+b) and len(chk)>x:
                s-=min(0,chk[x])
                x+=1
            ans=max(ans,s)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
import sys
sys.setrecursionlimit(10 ** 7)

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# 持っている宝石をDに詰めるのは最後
N, K = lr()
V = lr()
answer = 0
V = V[::-1] + V[::-1]
for x in range(K+1):
    # x回Dから取り出す、K-x回戻すことが可能
    x = min(x, N)
    for i in range(N-1, N-1+x+1):
        take = V[i-x+1:i+1]
        take.sort(reverse=True)
        result = sum(take)
        if result > answer:
            answer = result
        for j in range(K-x):
            if take:
                result -= take.pop()
                if result > answer:
                    answer = result

print(answer)

Submission status: Accepted

Solution code:
# python 3.4.3
import sys
input = sys.stdin.readline

# -------------------------------------------------------------
# library
# -------------------------------------------------------------



# -------------------------------------------------------------
# main
# -------------------------------------------------------------
from collections import deque
import heapq

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

ans = 0

maxPop = min(N,K)
# 左popする回数
for li in range(maxPop+1):
    # 右popする回数
    for ri in range(maxPop+1-li):
        # 初期化
        D = deque(V)
        jew = [] # 手持ちの宝石

        # pushの最大値
        maxPush = K - (ri+li)
        # 左popする
        for i in range(li):
            jew.append(D.popleft())
        # 右popする
        for i in range(ri):
            jew.append(D.pop())
        # 価値順にソート
        jew.sort()
        # push最大値の回数まで、負の価値の宝石をpushする（手持ちの価値を0にする）
        for i in range(min(maxPush, len(jew))):
            if jew[i] < 0:
                jew[i] = 0
        # 合計
        ans = max(ans,sum(jew))

print(ans)

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


def main():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    _V = V[::-1]

    ans = 0
    for k in range(K + 1):
        n_pop = min(k, N)
        n_push = K - n_pop
        for i in range(n_pop + 1):
            l, r = i, n_pop - i
            L = V[:l] + _V[:r]
            L.sort()
            for j in range(min(n_pop, n_push)):
                if L[j] < 0:
                    L[j] = 0
                else:
                    break
            v = sum(L)
            if v > ans:
                ans = v

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
input_nums = lambda: list(map(int, input().split()))
from collections import deque

def main():
    N, K = input_nums()
    V = input_nums()
    maxv = 0
    for total in range(min(N, K)+1):
        for a in range(total+1):
            D = deque(V)
            gems = []
            b = total - a
            for i in range(a):
                gems.append(D.pop())
            for i in range(b):
                gems.append(D.popleft())
            gems.sort(reverse=True)
            d = K - (a+b)
            for i in range(d):
                if len(gems) > 0:
                    a = gems.pop()
                    if a < 0:
                        continue
                    else:
                        gems.append(a)
                        break
            maxv = max(maxv, sum(gems))
    print(maxv)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

import sys
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import product                # product(iter, repeat=n)
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from fractions import gcd                    # for Python3.4.3
import math

def main():
    mod = 10000007                  # 10^9+7
    inf = float('inf')
    input = sys.stdin.readline      # 改行文字が残ることに注意
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def ii():  return int(input())
    def mi():  return map(int, input().rstrip().split())
    def lmi(): return list(map(int, input().rstrip().split()))
    def li():  return list(input().rstrip())
    
    
    n, k = mi()
    v = lmi()
    # i ... トータルの操作の回数。0 to k 回が許されている
    # 2n 回以上操作を行う意味はない。(2n 回で任意のレパートリーにできる)
    ans = -inf
    k = min(2*n, k)
    for i in range(k+1):    # O(10**2)
        for get_num in range(math.ceil(i/2), min(i+1, n+1)):    # O(50)
            return_num = i - get_num
            # print(f"get{get_num} ret{return_num} tot{i}")
            for from_left in range(get_num+1):    # O(75)
                from_right = get_num - from_left
                # print(f"left{from_left} right{from_right}")
                if from_right == 0:
                    L = v[:from_left]
                else:
                    L = v[:from_left] + v[-from_right:]
                ans = max(ans, sum(sorted(L)[return_num:]))    # O(xlgx (x=0 to 100))
    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 i in range(1, k + 1):
    if i <= n:
        for j in range(i + 1):
            l = v[:j] + v[n - i + j:]
            l.sort()
            kari = sum(l)
            for x in range(min(k - i, i)):
                if l[x] >= 0:
                    break
                kari -= l[x]
            ans = max(ans, kari)

print(ans)

Submission status: Accepted

Solution code:
mod = 10 ** 9 + 7
from collections import deque
import heapq


def iip(listed):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret


def main():
    r = solve()
    print(r)


def solve():
    N, K = iip(False)
    V = iip(True)
    V2 = [i for i in V]
    V2.reverse()

    mm = 0
    for i in range(N+1):
        for j in range(N+1):
            if i+j > K:
                continue
            if i+j > N:
                continue

            jewels = V[:i]
            jewels.extend(V2[:j])

            zyokyo = K - (i+j)

            while zyokyo >= 1:
                zyokyo -= 1
                if not jewels:
                    break
                mj = min(jewels)
                if min(jewels) < 0:
                    jewels.remove(mj)
                else:
                    break

            mm = max(mm, sum(jewels))
    return mm


#####################################################ライブラリ集ここから

def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def koenai_saidai_x_index(sorted_list, n):
    l = 0
    r = len(sorted_list)
    if len(sorted_list) == 0:
        return False
    if sorted_list[0] > n:
        return False

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] == n:
            return x
        elif sorted_list[x] > n:
            r = x
        else:
            l = x
    return l


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        # print(sorted_list)
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2) ** 2) % mod
    if p % 2 == 1:
        return (n * power(n, p - 1)) % mod


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
mod = 10 ** 9 + 7
from collections import deque
import heapq


def iip(listed):
    ret = [int(i) for i in input().split()]
    if len(ret) == 1 and not listed:
        return ret[0]
    return ret


def main():
    r = solve()
    print(r)


def solve():
    N, K = iip(False)
    V = iip(True)

    gsize = N+1

    dp1 = [[None for i in range(gsize)] for i in range(gsize)]
    dp1[0][0] = 0
    for i, value in enumerate(V, 1):
        for j in range(gsize):
            if dp1[i-1][j] is not None:
                dp1[i][j] = dp1[i-1][j] + value

            v = dp1[i-1][j-1]
            if j >= 1 and dp1[i-1][j-1] is not None:
                vv = dp1[i][j]
                if vv is not None:
                    v = max(v, vv)
                dp1[i][j] = v

    V.reverse()
    dp2 = [[None for i in range(gsize)] for i in range(gsize)]
    dp2[0][0] = 0
    for i, value in enumerate(V, 1):
        for j in range(gsize):
            if dp2[i - 1][j] is not None:
                dp2[i][j] = dp2[i - 1][j] + value

            v = dp2[i - 1][j - 1]
            if j >= 1 and dp2[i - 1][j - 1] is not None:
                vv = dp2[i][j]
                if vv is not None:
                    v = max(v, vv)
                dp2[i][j] = v

    mm = 0
    for i1 in range(gsize):
        for j1 in range(gsize):
            for i2 in range(gsize):
                for j2 in range(gsize):
                    if dp1[i1][j1] is None:
                        continue
                    if dp2[i2][j2] is None:
                        continue

                    kh = dp1[i1][j1]+dp2[i2][j2]
                    if i1 + i2 + j1 + j2 > K:
                        continue
                    if i1 + i2 > N:
                        continue

                    mm = max(kh, mm)


    #for j in dp1:
    #    print(j)
    #for j in dp2:
    #    print(j)

    return mm


#####################################################ライブラリ集ここから

def split_print_space(s):
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):
    print("\n".join([str(i) for i in s]))


def koenai_saidai_x_index(sorted_list, n):
    l = 0
    r = len(sorted_list)
    if len(sorted_list) == 0:
        return False
    if sorted_list[0] > n:
        return False

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] == n:
            return x
        elif sorted_list[x] > n:
            r = x
        else:
            l = x
    return l


def searchsorted(sorted_list, n, side):
    if side not in ["right", "left"]:
        raise Exception("sideはrightかleftで指定してください")

    l = 0
    r = len(sorted_list)

    if n > sorted_list[-1]:
        # print(sorted_list)
        return len(sorted_list)
    if n < sorted_list[0]:
        return 0

    while r - l > 1:
        x = (l + r) // 2
        if sorted_list[x] > n:
            r = x
        elif sorted_list[x] < n:
            l = x
        else:
            if side == "left":
                r = x
            elif side == "right":
                l = x

    if side == "left":
        if sorted_list[l] == n:
            return r - 1
        else:
            return r

    if side == "right":
        if sorted_list[l] == n:
            return l + 1
        else:
            return l


def soinsuu_bunkai(n):
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):
    return power(n, mod - 2)


def power(n, p):
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2) ** 2) % mod
    if p % 2 == 1:
        return (n * power(n, p - 1)) % mod


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
X = list(map(int, input().split()))
r = -10**18
for i in range(-1, N):
#    print(i)
    for j in range(i+1, N+1):
        A, B = X[:i+1], X[j:]
        if i+1+N-j > K:
            continue
        C = sorted(A+B)[::-1]
#        print(A, B, i+1, N-j, i, j)
        for _ in range(K-(i+1+N-j)):
            if not C:
                break
            c = C.pop()
            if c > 0:
                C.append(c)
                break
        r = max(r, sum(C))
print(r)

Submission status: Accepted

Solution code:
from collections import deque
import heapq

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

ans = 0
for i in range(1,min(n,k)+1):
    for j in range(i+1):
        s = []
        heapq.heapify(s)
        res = 0
        num = 0
        for _ in range(j):
            heapq.heappush(s,v[num])
            res += v[num]
            num += 1
        num = 1
        for _ in range(j,i):
            heapq.heappush(s,v[-num])
            res += v[-num]
            num += 1

        for j in range(k-i):
            if len(s) == 0:
                break
            if s[0] < 0:
                res -= heapq.heappop(s)
            else:
                break
        if ans < res:
            ans = res
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
import heapq

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


#a : heapq.heappop(s,v.popleft())
#b : heapq.heappop(s,v.pop())
#c : v.appendleft(heapq.heappop(s))
#d : v.append(heapq.heappop(s))
ans = 0
for i in range(1,min(n,k)+1):
    for j in range(i+1):
        s = []
        heapq.heapify(s)
        res = 0
        num = 0
        for _ in range(j):
            heapq.heappush(s,v[num])
            res += v[num]
            num += 1
        num = 1
        for _ in range(j,i):
            heapq.heappush(s,v[-num])
            res += v[-num]
            num += 1

        for j in range(k-i):
            if len(s) == 0:
                break
            if s[0] < 0:
                res -= heapq.heappop(s)
            else:
                break
        if ans < res:
            ans = res
    #print(i,ans)
print(ans)

Submission status: Accepted

Solution code:
import numpy as np

def main():
    N, K = [int(i) for i in input().split()]
    v = [int(i) for i in input().split()]
    res = 0
    max_ext = min(K, N)
    for ext in range(1, max_ext + 1):
        for a in range(ext+1):
            v_ext = v[:a]
            if a < ext:
                v_ext += v[-(ext-a):]
            v_ext = sorted(v_ext)
            max_ret = K - ext
            cnt_neg = 0
            for i in range(min(max_ret, ext)):
                if v_ext[i] < 0:
                    cnt_neg += 1
            res = max(res, sum(v_ext[cnt_neg:]))

    print(res)



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def resolve():
    n, k = map(int, input().split())
    v = list(map(int, input().split()))
    ans=0
    minus=0
    for i in range(k+1):
        for j in range(i+1):
            if j<=n:
              for t in range(j+1):
                w=sorted(v[:j-t] + v[n -t:])
                for l in w[:i-j]:
                    if l<0:
                       minus+=l
                ans=max(ans,(sum(w)-minus))
                minus=0
            else:
                for t in range(j + 1):
                    w = sorted(v)
                    for l in w[:i - j]:
                        if l < 0:
                            minus += l
                    ans = max(ans, (sum(w) - minus))
                    minus = 0
    print(ans)
resolve()

Submission status: Accepted

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

ops = min(N,K)

ans = 0
for A in range(0,ops+1):
    l = V[:A]
    l.sort()
    for B in range(0,ops+1-A):
        ll = l[:]
        if B > 0:
            ll = l + V[-B:]
            ll.sort()
        for i in range(0,min(K-(A+B),A+B)):
            if ll[i] < 0:
                ll[i] = 0
            else:
                break
        ans = max(sum(ll),ans)

print(ans)

Submission status: Accepted

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


def dfs(left, right, k):
    if left > right:
        return 0
    if k == 0:
        return 0
    if (left, right, k) in memo:
        return memo[(left, right, k)]

    l1 = V[left] + dfs(left + 1, right, k - 1)
    l2 = dfs(left + 1, right, k - 2) if k >= 2 else 0
    r1 = V[right] + dfs(left, right - 1, k - 1)
    r2 = dfs(left, right - 1, k - 2) if k >= 2 else 0
    memo[(left, right, k)] = max([l1, l2, r1, r2, 0])
    return memo[(left, right, k)]


memo = {}
print(dfs(0, n-1, k))

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
V = list(map(int,input().split()))
take_chance = min(N,K)
ans = 0
for A in range(take_chance+1):
    for B in range(take_chance-A+1):
        sum1 = 0
        take = sorted(V[0:A] + V[N-B:N])
        suteru_chance = min(len(take),K-(A+B))
        sum1 = sum(take)
        for i in range(suteru_chance):
            if(take[i]<0):
                sum1 -= take[i]
        ans = max(ans,sum1)
print(ans)

Submission status: Accepted

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

ans = -1 * float("INF")
for l in range(K+1):
  for r in range(K+1-l):
    if l + r > N:
      break
    d = K - l - r
    s = V[0:l] + V[N-1:N-1-r:-1]
    value = sum(s)
    s.sort()
    for i in range(d):
      if i >= len(s):
        break
      if s[i] < 0:
        value -= s[i]
      else:
        break
    ans = max(ans, value)
print(ans)