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: Wrong Answer

Solution code:
import time
startTimeProblem=time.time()

import fileinput, sys, itertools, functools
from math import *
from bisect import *
from heapq import *
from collections import *

def lcm(a, b):  
    return (a*b)/gcd(a, b)

class InputHelper:
    def __init__(self):
        self.myinput = fileinput.input()

    def isLocal(self):
        return not fileinput.isstdin()

    def int(self):
        return int(self.myinput.readline().rstrip())

    def ints(self):
        return [int(_) for _ in self.myinput.readline().rstrip().split()]

    def str(self):
        return self.myinput.readline().rstrip()

    def strs(self):
        return [_ for _ in self.myinput.readline().rstrip().split()]

class OutputHelper:
    def int(self, a):
        print(a)    

    def ints(self, a):  
        print(" ".join([str(_) for _ in a]))
    
    def intsNL(self, a):
        for _ in a:
            print(_)
    
    def str(self, s):
        print(s)

    def strs(self, s):
        print(" ".join([_ for _ in s]))

    def strsNL(self, s):
        for st in s:
            print(st)

class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None
        self.prev = None

In = InputHelper()
Out = OutputHelper()

######################################

N, K = In.ints()
V = In.ints()

class Solution():
    def __init__(self, K, V):
        self.ans = 0
        self.k = K
        self.posSum = 0
        self.negPreSum = [0]
        self.V = V

    @functools.lru_cache(None)
    def rec(self, fromIncl, toIncl):
        self.k -= 1
        canCallNext = self.k>0 and fromIncl!=toIncl

        #taketh left part
        leftVal = self.V[fromIncl]
        if leftVal>=0:
            self.posSum+=leftVal
        else:
            self.negPreSum.append(self.negPreSum[-1]+leftVal)

        negIdx = max(0, len(self.negPreSum)-1-self.k)
        self.ans = max(self.ans, self.posSum+self.negPreSum[negIdx])

        if canCallNext:
            self.rec(fromIncl+1, toIncl)
        
        if leftVal>=0:
            self.posSum-=leftVal
        else:
            self.negPreSum.pop(-1)
        
        #taketh right
        rightVal = self.V[toIncl]
        if rightVal>=0:
            self.posSum+=rightVal
        else:
            self.negPreSum.append(self.negPreSum[-1]+rightVal)

        negIdx = max(0, len(self.negPreSum)-1-self.k)
        self.ans = max(self.ans, self.posSum+self.negPreSum[negIdx])

        if canCallNext:
            self.rec(fromIncl, toIncl-1)

        if rightVal>=0:
            self.posSum-=rightVal
        else:
            self.negPreSum.pop(-1)

        self.k += 1


sol = Solution(K, V)
sol.rec(0, N-1)
Out.int(sol.ans)

######################################

if len(sys.argv)>2 and sys.argv[2]=="TIMEIT":
    fin = (time.time()-startTimeProblem)*1000
    print("{:.2f}".format(fin) + "ms")

Submission status: Wrong Answer

Solution code:
def solve():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    V *= 2
    ans = 0
    for i in range(N+1):
        for j in range(N-1,2*N):
            num = j-i+1
            if num>K or num == 0:
                continue
            lis = V[i:j+1]
            lis.sort()
            margin = K-num
            m = sum(lis)
            k = 0
            while k < margin and k < num and lis[k]<0 :
                m -= lis[k]
                k += 1
            ans = max(ans,m)
    return ans
print(solve())

Submission status: Wrong Answer

Solution code:
#template
def inputlist(): return [int(k) for k in input().split()]
#template
N,K = inputlist()
V = inputlist()
n = min(N,K)
ans = 0
from collections import deque
for a in range(n+1):
    for b in range(n+1):
        li = []
        if a+b > n:
            continue
        c = n-(a+b)
        que = deque(V)
        for i in range(a):
            k = que.popleft()
            li.append(k)
        for j in range(b):
            s = que.pop()
            li.append(s)
        li.sort()
        index = 0
        for i in range(len(li)):
            if li[i] < 0:
                index +=1
        na = min(index,c)
        suma = sum(li[na:])
        ans = max(ans,suma)

print(ans)

Submission status: Wrong Answer

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

#take i and remove K-i
answer=0
for i in range(1,K):
  if i>N: break
  
  take_cand=[]
  if i>=N:
    take_cand=[vlist[:]]
  else:
    for j1 in range(i+1):
      j2=i-j1
      take_cand.append(vlist[:j1]+vlist[N-j2:])
  
  #print(i,take_cand)
  for take in take_cand:
    take.sort(reverse=True)
    for _ in range(K-i):
      if len(take)>0 and take[-1]<0:
        take.pop()
    
    answer=max(sum(take),answer)

print(answer)

Submission status: Wrong Answer

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

#take i and remove K-i
answer=0
for i in range(K):
  take_cand=[]
  if i>=N:
    take_cand=[vlist]
  else:
    for j1 in range(i+1):
      j2=i-j1
      take_cand.append(vlist[:j1]+vlist[N-j2:])
  
  #print(i,take_cand)
  for take in take_cand:
    take.sort(reverse=True)
    for _ in range(K-i):
      if len(take)>0 and take[-1]<0:
        take.pop()
    
    answer=max(sum(take),answer)

print(answer)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
ma = 0
kaisu = min(n,k)
for a in range(kaisu+1):
    for b in range(kaisu-a+1):
        amari = k-a-b
        if b == 0:
            li = v[:a]
        else:
            li = v[:a]+v[-b:]
        li.sort()
        for p in range(amari):
            if li:
                li.pop(0)
        ma = max(ma,sum(li))
print(ma)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
ma = 0
kaisu = min(n,k)
for a in range(kaisu+1):
    for b in range(kaisu-a+1):
        amari = k-a-b
        if b == 0:
            li = v[:a]
        else:
            li = v[:a]+v[-b:]
        li.sort()
        li = li[amari:]
        ma = max(ma,sum(li))
print(ma)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
ma = 0
for a in range(k+1):
    for b in range(k-a+1):
        if a+b > n:
            continue
        amari = k-a-b
        if b == 0:
            li = v[:a]
        else:
            li = v[:a]+v[-b:]
        li.sort()
        li = li[amari:]
        ma = max(ma,sum(li))
print(ma)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
ma = 0
#最後に返せばよい
for a in range(n+1):
    for b in range(n-a+1):
        li = v[:a]+v[n-b:]
        if a+b > k:
            continue
        if a+b > n:
            continue
        push = k-a-b
        li.sort()
        li = li[push:]
        ma = max(ma,sum(li))
print(ma)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
ma = 0
#最後に返せばよい
for a in range(n+1):
    for b in range(n-a+1):
        li = v[:a]+v[n-b:]
        if a+b > k:
            continue
        push = k-a-b
        if a+b < push:
            continue
        li.sort()
        li = li[push:]
        ma = max(ma,sum(li))
print(ma)

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
ma = 0
#最後に返せばよい
for a in range(k+1):
    for b in range(k-a+1):
        li = v[:a]+v[n-b:]
        push = k-a-b
        if a+b > n:
            continue
        if a+b < push:
            continue
        li.sort()
        li = li[push:]
        ma = max(ma,sum(li))
print(ma)

Submission status: Wrong Answer

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

#最後に返せばよい
for a in range(k+1):
    for b in range(k-a+1):
        """
        if a+b > n:
            continue
        """
        li = v[:a]+v[n-b:]
        push = k-a-b
        li.sort()
        li = li[push:]
        ma = max(ma,sum(li))

print(ma)

Submission status: Wrong Answer

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

#最後に返せばよい
for a in range(k+1):
    for b in range(k-a+1):
        if a+b > n:
            continue
        li = v[:a]+v[n-b:]
        push = k-a-b
        li.sort()
        li = li[push:]
        ma = max(ma,sum(li))

print(ma)

Submission status: Wrong Answer

Solution code:
def main():
    n, k = map(int, input().split())
    v = [int(x) for x in input().split()]
    
    ans = 0
    for i in range(min([n, k])):
        for j in range(min([n, k])-i):
            if i+j > k or i+j > n:
                continue
            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: Wrong Answer

Solution code:
def main():
    n, k = map(int, input().split())
    v = [int(x) for x in input().split()]
    
    ans = 0
    for i in range(min([n, k])):
        for j in range(min([n, k])-i):
            if i+j > k or i+j > n:
                continue
            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: Wrong Answer

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 > k and minus_list:
                minus_count -= 1
                sub -= heapq.heappop(minus_list)
            
            if i+(n-j)+minus_count > k:
                break
            if ans < sub:
                ans = sub
        
        
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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 = (-1)*pow(10, 10)
    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 > k and minus_list:
                minus_count -= 1
                sub -= heapq.heappop(minus_list)
            
            if i+(n-j)+minus_count > k:
                break
            if ans < sub:
                ans = sub
        
        
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,k = map(int,input().split())
v = list(map(int,input().split()))
r = min(n,k)
ans,S = sum(v),sum(v)
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: Wrong Answer

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 = max(0, 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: Wrong Answer

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 = max(0, 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-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: Wrong Answer

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 = K - lk
        if rk>0:
            q = V[:lk][::-1] + V[-rk:]
        else:
            q = V[:lk][::-1]
        
        m = 0
        sum_=0

        for i in range(len(q)):
            q_ = q[i:]
            m = i
            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-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: Wrong Answer

Solution code:
N,K = map(int,input().split())
V = list(map(int,input().split()))
r = min(N,K)
ans = 0
for a in range(r+1):
    for b in range(r+1):
        if a + b > K:
            continue
        d = r - (a + b)
        temp = []
        if a != 0:
            temp += V[:a]
        if b != 0:
            temp += V[N-b:]
        #print(a,b,temp)
        temp.sort()
        s = sum(temp)
        for i in range(min(d,len(temp))):
            if temp[i] < 0:
                s -= temp[i]
        ans = max(ans,s)
print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
V = list(map(int,input().split()))
r = min(N,K)
ans = 0
for a in range(r+1):
    for b in range(r+1):
        if a + b > K:
            break
        d = r - (a + b)
        temp = []
        if a != 0:
            temp += V[:a]
        if b != 0:
            temp += V[N-b:]
        #print(a,b,temp)
        temp.sort()
        s = sum(temp)
        for i in range(min(d,len(temp))):
            if temp[i] < 0:
                s -= temp[i]
        ans = max(ans,s)
print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
V = list(map(int,input().split()))
r = min(N,K)
ans = 0
for a in range(r+1):
    for b in range(r+1-a):
        d = r - (a + b)
        temp = []
        if a != 0:
            temp += V[:a]
        if b != 0:
            temp += V[N-b:]
        #print(a,b,temp)
        temp.sort()
        s = sum(temp)
        for i in range(min(d,len(temp))):
            if temp[i] < 0:
                s -= temp[i]
        ans = max(ans,s)
print(ans)

Submission status: Wrong Answer

Solution code:
N,K = map(int,input().split())
V = list(map(int,input().split()))
r = min(N,K)
ans = 0
for a in range(r+1):
    for b in range(r+1-a):
        d = r - (a + b)
        temp = []
        if a != 0:
            temp += V[:a]
        if b != 0:
            temp += V[-b:]
        #print(a,b,temp)
        temp.sort()
        s = sum(temp)
        for i in range(min(d,len(temp))):
            if temp[i] < 0:
                s -= temp[i]
        ans = max(ans,s)
print(ans)

Submission status: Wrong Answer

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)
        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: Wrong Answer

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

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):
    # 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: Wrong Answer

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

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

# 持っている宝石をDに詰めるのは最後
N, K = lr()
V = lr()
answer = - 10**15
V = V[::-1] + V[::-1]
for x in range(K):
    # 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: Wrong Answer

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 = - 10**15
V = V[::-1] + V[::-1]
for x in range(K):
    # 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: Wrong Answer

Solution code:
# coding: utf-8
import sys

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

# 持っている宝石をDに詰めるのは最後
N, K = lr()
V = lr()
answer = - 10**15
V = V[::-1] + V[::-1]
for x in range(K):
    # 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: Wrong Answer

Solution code:
# coding: utf-8
import sys

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

# 持っている宝石をDに詰めるのは最後
N, K = lr()
V = lr()
answer = - 10**15
V = V[::-1] + V[::-1]
limit = min(K, N)
for x in range(K):
    # x回Dから取り出す、K-x回戻すことが可能
    x = min(x, N)
    for i in range(N-1, N-1+x):
        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: Wrong Answer

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 = maxPop - (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: Wrong Answer

Solution code:
# D
n, k = map(int, input().split())
v = list(map(int, input().split()))
q = []
ans = 0
for a in range(min(n, k)):
    for b in range(min(n, k) - a ):
        # print(a, b)
        if a == 0:
            pass
        else:
            q.extend(v[:a])
        if b == 0:
            pass
        else:
            q.extend(v[-b:])
        q.sort()
        pick = k - (a + b)
        for i in range(min(pick, len(q))):
            # print(i, q)
            if q[0] < 0:
                q.reverse()
                q.pop()
                q.reverse()
            else:
                break
        s = sum(q)
        # print(q, pick, q[:pick], s)
        if ans < s:
            ans = s
        q.clear()
print(ans)

Submission status: Wrong Answer

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


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 return_num in range(i//2+1):    # O(10**2)
            get_num = i - return_num
            # print(f"get{get_num} ret{return_num} tot{i}")
            for from_left in range(get_num+1):    # O(10**2)
                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(10**2 log 10**2)
    print(ans)




if __name__ == "__main__":
    main()