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 sys
from heapq import heappop, heappush

def main():
    input = sys.stdin.readline
    N, K = map(int, input().split())
    V = list(map(int, input().split()))

    ans = 0
    for left in range(min(N, K)):
        for right in range(min(N, K) - left):
            heap = []
            for v in V[:left]:
                heappush(heap, v)

            for v in V[N - right:]:
                heappush(heap, v)

            cnt = left + right
            while cnt < K and len(heap) > 0:
                v = heappop(heap)
                if v > 0:
                    heappush(heap, v)
                    break

                cnt += 1

            ans = max(ans, sum(heap))

    return ans


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

Submission status: Wrong Answer

Solution code:
import copy
N,KK = map(int,input().split())
V = list(map(int,input().split()))
# N = 40
# K = 100
# V = [i for i in range(N)]

# V = [0 for i in range(N)] + V + [0 for i in range(N)] 

sumval = 0
for K in range(KK+1):
    for sute in range(K):
        for i in range(K-sute):
            # print(V[:K-sute-i], V[N-i:])
            sV = sorted(V[:K-sute-i]+ V[N-i:])
            # print(sV[sute:])
            sumval = max(sum(sV[sute:]),sumval)

print(sumval)

Submission status: Wrong Answer

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

l = []
ans = 0
for a in range(K + 1):
  for b in range(K + 1 - a):
    l = V[:a] + V[N - b:]
    l.sort()
    for _ in range(K - a - b):
      if len(l) > 0 and l[0] < 0:
        l.pop(0)
      else:
        break
    ans = max(ans, sum(l))

print(ans)

Submission status: Wrong Answer

Solution code:
n, k = [int(i) for i in input().split()]
vs = [int(i) for i in input().split()]
u = min(k, n)

def func(num):
    ans = 0
    for i in range(num + 1):
        # tmp = vs[:i]
        # print(i, u - num + 1)
        for j in range(u - num + 1):
            # print(vs[:i], vs[::-1][:j])
            tmp = vs[:i] + vs[::-1][:j]

            # print(tmp)

            tmp.sort()
            # print(tmp, num, i, num - i)
            for j in range(u - i - j):
                if not tmp or tmp[0] >= 0:
                    break
                tmp.pop(0)

            # print(tmp)
            ans = max(ans, sum(tmp))
    return ans


ans = 0
# u = min(k, n)
for i in range(u + 1):
    tmp = func(i)
    ans = max(ans, tmp)
    # print(i, u - i, func(i, 0), func(u - i, 1))
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy


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


memo = {}


def best_op(v_list, hand, k):
    # print('call ', v_list, hand, k)
    if (tuple(v_list.tolist()), tuple(hand.tolist()), k) in memo:
        # print('hit')
        return memo[(tuple(v_list.tolist()), tuple(hand.tolist()), k)]
    if k == 0:
        # print('return')
        return sum(hand)
    if k > 0:
        # print('a')
        # print(v_list, hand)
        v_list_a, hand_a, succ = op_a(v_list, hand)
        if succ:
            sum_a = best_op(v_list_a, hand_a, k - 1)
            if not (tuple(v_list_a.tolist()), tuple(hand_a.tolist()), k - 1) in memo:
                memo[(tuple(v_list_a.tolist()), tuple(hand_a.tolist()), k - 1)] = sum_a
        else:
            sum_a = -10 ** 7 * k

        # print('b')
        # print(v_list, hand)
        v_list_b, hand_b, succ = op_b(v_list, hand)
        if succ:
            sum_b = best_op(v_list_b, hand_b, k - 1)
            if not (tuple(v_list_b.tolist()), tuple(hand_b.tolist()), k - 1) in memo:
                memo[(tuple(v_list_b.tolist()), tuple(hand_b.tolist()), k - 1)] = sum_b
        else:
            sum_b = -10 ** 7 * k

        # print('c')
        v_list_c, hand_c, succ = op_c(v_list, hand)
        if succ and hand[0] > 0:
            sum_c = best_op(v_list_c, hand_c, k - 1)
            if not (tuple(v_list_c.tolist()), tuple(hand_c.tolist()), k - 1) in memo:
                memo[(tuple(v_list_c.tolist()), tuple(hand_c.tolist()), k - 1)] = sum_c
        else:
            sum_c = -10 ** 7 * k

        # print('d')
        v_list_d, hand_d, succ = op_d(v_list, hand)
        if succ and hand[0] > 0:
            sum_d = best_op(v_list_d, hand_d, k - 1)
            if not (tuple(v_list_d.tolist()), tuple(hand_d.tolist()), k - 1) in memo:
                memo[(tuple(v_list_d.tolist()), tuple(hand_d.tolist()), k - 1)] = sum_d
        else:
            sum_d = -10 ** 7 * k

        v_list_e, hand_e, succ = v_list, hand, True
        sum_e = best_op(v_list_e, hand_e, k - 1)

        # print(sum_a, sum_b, sum_c, sum_d)
        return max(sum_a, sum_b, sum_c, sum_d, sum_e)


def op_a(v_list, hand):
    if len(v_list) == 0:
        return v_list, hand, False
    value = v_list[0]
    v_list = numpy.delete(v_list, 0)
    hand = numpy.append(hand, value)
    hand.sort()
    return v_list, hand, True


def op_b(v_list, hand):
    if len(v_list) == 0:
        return v_list, hand, False
    value = v_list[len(v_list) - 1]
    v_list = numpy.delete(v_list, len(v_list) - 1)
    hand = numpy.append(hand, value)
    hand.sort()
    return v_list, hand, True


def op_c(v_list, hand):
    if len(hand) == 0:
        return v_list, hand, False
    min_val = hand[0]
    hand = numpy.delete(hand, 0)
    v_list = numpy.insert(v_list, 0, min_val)
    return v_list, hand, True


def op_d(v_list, hand):
    if len(hand) == 0:
        return v_list, hand, False
    min_val = hand[0]
    hand = numpy.delete(hand, 0)
    v_list = numpy.append(v_list, min_val)
    return v_list, hand, True


if __name__ == '__main__':
    [n, k] = li()
    v_list = li()
    v_list = numpy.array(v_list, dtype=numpy.int64)
    hand = numpy.array([], dtype=numpy.int64)

    # print(n, k)
    # print(v_list)
    print(max(best_op(v_list, hand, k), 0))

Submission status: Wrong Answer

Solution code:
import sys
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from copy import copy
import numpy as np
from numpy.fft import fft, ifft
from fractions import gcd


def input(): return sys.stdin.readline().strip()


def INT(): return int(input())


def MAP(): return map(int, input().split())


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


sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

n, k = MAP()

v = LIST()

m = int(n) + 1


lis = []
for h in range(k+1):
    for i in range(h):
        j = i - h+1
        #print(i,j)
        if j==0:
            #print(v[:i])
            lis.append(v[:i])
        else:
            #print(v[:i] + v[j:])
            lis.append(v[:i]+v[j:])

ans=0

for x in lis:
    a = x.copy()
    a.sort()
    for i in range(1, k - len(x) + 1):
        if a == []:
            break
        else:
            a.pop(0)
            #print(a)
            ans = max(ans, sum(a))

print(ans)

Submission status: Wrong Answer

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

for i in range(1,N+1):#何個取るか
    for r in range(i+1):
        l=i-r
        a=V[:i]
        b=V[N-l:]
        f=max(0,K-r-l)
        c=a+b
        c.sort()
        k=0
        t=0
        for j in c:
            if t<f and j<0:
                t+=1
                continue
            k+=j
        ans=max(ans,k)
print(ans)

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
v = list(map(int, input().split()))
cum = [0] * (n+1)

for i in range(n):
    cum[i+1] = cum[i] + v[i]

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

print(ans)

Submission status: Wrong Answer

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

results = []
for a in range(n + 1):
    for b in range(k - a + 1):
        p = v[:a] + v[n - b:]
        p.sort()
        for i in range(k - a - b + 1):
            results.append(sum(p[i:]))
print(max(results))

Submission status: Wrong Answer

Solution code:
n,k=map(int,input().split())
v = list(map(int, input().split()))
cum = [0] * (n+1)

for i in range(n):
    cum[i+1] = cum[i] + v[i]

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

print(ans)

Submission status: Wrong Answer

Solution code:
N, K = (int(x) for x in input().split())
V = [int(x) for x in input().split()]
ans = 0
for left in range(K+1):
    for right in range(K+1-left):
        back = K - left - right
        tmp_list = V[:left] + V[N-right:]
        tmp_list.sort()
        index = 0
        t = min(len(tmp_list), back)
        for i in range(t):
            index += 1
            if tmp_list[i] >= 0:
                break
        tmp = sum(tmp_list[index:])
        if tmp > ans:
            ans = tmp

print(ans)

Submission status: Wrong Answer

Solution code:
import copy
N,K = map(int,input().split())
V = list(map(int,input().split()))
# N = 40
# K = 100
# V = [i for i in range(N)]

# V = [0 for i in range(N)] + V + [0 for i in range(N)] 

sumval = 0
for sute in range(K):
    for i in range(K-sute):
        # print(V[:K-sute-i], V[N-i:])
        sV = sorted(V[:K-sute-i]+ V[N-i:])
        # print(sV[sute:])
        sumval = max(sum(sV[sute:]),sumval)

print(sumval)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun May 26 22:52:59 2019

@author: Yamazaki Kenichi
"""
N,K = map(int,input().split())
V = list(map(int,input().split()))

if N < K:
    K = N

ans = 0
for i in range(K):
    for j in range(K-i+1):
        tmp = 0
        minus = [0]
        for k in range(K-i):
            tmp += V[k-j] if V[k-j] > 0 else 0
            
#            heapq.heappush(minus,V[k-j])
##            print(tmp,minus)
#        for k2 in range(i):
#            if minus[0] < 0:
#                tmp += (-heapq.heappop(minus))
#            else:
#                break
#        print(ans,tmp,i,j,k)
        ans = max(ans,tmp)
    
print(ans)

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
V = list(map(int, input().split()))
ans = 0
for pull in range(k + 1):
    for back in range(k):
        if pull + back != k:
            continue
        for l in range(pull+1):
            r = pull - l
            if r > 0:
                hand = V[:l] + V[-r:]
            else:
                hand = V[:l]
            hand = sorted(hand, reverse=True)
            for _ in range(back):
                if len(hand) == 0:
                    break
                if hand[-1] < 0:
                    hand.pop()
                else:
                    break
            ans = max(ans, sum(hand))
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(100000)

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


ans = 0
for i in range(K+1):
  hand = V[:i]
  for j in range(K-i+1):
    if j != 0:
      x = hand + V[-j:]
    else:
      x = hand
    rest = K - i - j
    summ = sum(v for i, v in enumerate(sorted(x)) if i >= rest or v > 0)
    ans = max(ans, summ)
    # print(f"K={K}, i={i}, j={j}, rest={rest}, sum={summ}, x={x}")
print(ans)

Submission status: Wrong Answer

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


cap = min(n, k)
max_val = 0
for left in range(k):
    for right in range(cap - left):
        rest = k - (left + right)
        l_popped = v[:left]
        r_popped = v[-right:] if right > 0 else []
        popped = l_popped + r_popped

        popped.sort()

        first_positive = len(popped)
        for i, value in enumerate(popped):
            if value > 0:
                first_positive = i
                break

        sum_val = sum(popped[min(rest, first_positive):])
        if sum_val > max_val:
            max_val = sum_val

print(max_val)

Submission status: Wrong Answer

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

# 左からleft個、右からright個、返すのをret個とする。

result = 0
for left in range(min(N,K)+1):
    for right in range(min(K-left, N-left)+1):
        ll = V[0:left]
        rr = list(collections.deque(V, right))
        total = sorted(ll + rr)
        for ret in range(min(K-left-right, len(total))+1):
            del total[0:ret]
            res = total
            if result < sum(res):
                result = sum(res)

print(result)

Submission status: Wrong Answer

Solution code:
from sys import stdin

def main():
     def max_n_main(oku,kosu_s,kosu_e):
          if len(v)>=oku:
               ans = max_n_sub(oku,kosu_s,kosu_e,v[:oku])
               ans = max(ans,max_n_sub(oku,kosu_s,kosu_e,v[len(v)-oku+1:]))
               for i in range(1,oku):
                    tmpv = v[:i]+v[len(v)-oku+i:]
                    ans = max(ans,max_n_sub(oku,kosu_s,kosu_e,tmpv))
               return ans
          else:
               return 0
               
     def max_n_sub(oku,kosu_s,kosu_e,tmpv):#奥行きokuから個数kosu_sから個数kosu_eの間の個数をとる時価値が最大な値を返す
          tmpv.sort()
          ko = 0
          ans = 0
          for i in range(len(tmpv)):
               if ko < kosu_s:
                    ans += tmpv[len(tmpv)-i-1]
                    ko += 1
               else:
                    if ko == kosu_e:
                         break
                    elif tmpv[len(tmpv)-i-1]>0:
                         ans += tmpv[len(tmpv)-i-1]
                         ko += 1
                    else:
                         break
          return ans
          
     n,k= [int(x) for x in stdin.readline().split()]
     v = [int(x) for x in stdin.readline().split()]
     ans = 0
     for ki in range(1,k):
          ans = max(ans,max_n_main(ki,max(1,2*ki-k),ki))
     print(ans)
     return 0
     
if __name__ == '__main__':
     main()

Submission status: Wrong Answer

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

max = 0
for i in range(k+1):
    for j in range(i+1):
        sp = i - j
        msp = -j
        if msp == 0:
            msp = len(v_)
        d = []
        d.extend(v_[:sp])
        d.extend(v_[msp:])
        d.sort()
        retmax = sum(d)
        for p in range(min(len(d), k-i)):
            if d[p] < 0:
                retmax -= d[p]
        if retmax > max:
            max = retmax
print(max)

Submission status: Wrong Answer

Solution code:
import sys
from heapq import heappop, heappush

def main():
    input = sys.stdin.readline
    N, K = map(int, input().split())
    V = list(map(int, input().split()))

    ans = 0
    for left in range(min(N, K)):
        for right in range(min(N, K) - left):
            heap = []
            for v in V[:left]:
                heappush(heap, v)

            for v in V[::-1][:right]:
                heappush(heap, v)

            cnt = left + right
            while cnt < K and len(heap) > 0:
                v = heappop(heap)
                if v > 0:
                    heappush(heap, v)
                    break

                cnt += 1

            ans = max(ans, sum(heap))

    return ans


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

Submission status: Wrong Answer

Solution code:
N, K = [int(_) for _ in input().split()]
V_lis = [int(_) for _ in input().split()]

point_lis = []

for k in range(1, min(K+1, N+1)):
  
  val_lis = []
  point = 0
  
  for left_k in range(1, k+1):
    val_lis = V_lis[:left_k-1]
    if left_k < k:
      val_lis += V_lis[-(k-left_k):]

    point = sum(val_lis)
    num_of_neg = [_ for _ in val_lis if _ < 0]
    num_of_neg.sort()
  
    diff = K - k + 1
    if diff >= len(num_of_neg):
      point -= sum(num_of_neg)
    elif diff > 0:
      for x in range(diff):
        point -= num_of_neg[-x]
      
    point_lis.append(point)
  
print(max(point_lis))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
v = list(map(int, input().split()))
res = -(10 ** 7 * 50)
for r in range(min(n, k)+1, -1, -1):
    for i in range(r):
        j = r - i - 1
        if i != r - 1:
          
            v_sub = v[:i] + v[-j:]
        else:
            v_sub = v[:i]
        if len(v_sub) > 0:
            if r%2 != min(n,k)%2:
                res = max(res, sum(v_sub))
            else:
                res = max(res, sum(sorted(v_sub)[1:]))
                # if i != r - 1:
                #     res = max(res, sum(sorted(v[:i][:-1] + v[-j:])[1:]), sum(sorted(v[-j:][1:] + v[:i])[1:]))
                # else:
                #     res = max(res, sum(sorted(v[:i][:-1])[1:]))
print(max(res,0))

Submission status: Wrong Answer

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

# 何個捨てるか
ans = 0
for i in range(K):
    # 右から何個目まで取るか
    if K-i >= N:
        pick = q
        pick = sorted(pick)
        ans = max(sum(pick[i:]),ans)        
    else:
        pick = q[:K-i]
        pick = sorted(pick)
        ans = max(sum(pick[i:]),ans)
        for j in range(min(N,K-i)):
            pick = []
            pick = q[:j]+q[-(K-i-j):]
            pick = sorted(pick)
            ans = max(sum(pick[i:]),ans)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs,heapq as hq
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l():
	return list(map(int,input().split()))
def uy():
	return map(int,input().split())
def s(x):
	a = []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa == x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x):
	return " ".join(map(str,x))

n,m = uy()

a = l()

su = 0
for i in range(n+1):
	ll = max(i,n-(m - i))
	for j in range(ll,n+1):
		q = []
		co = 0
		p = a[:i]
		pp = a[j:]
		for k in range(len(p)):
			if p[k] < 0:
				hq.heappush(q,p[k])
		for k in range(len(pp)):
			if pp[k] < 0:
				hq.heappush(q,pp[k])
		co += sum(p)
		co += sum(pp)
		q.sort()
		for k in range(min(len(q),j-ll)):
			co += abs(hq.heappop(q))
		su = max(su,co)
print(su)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(100000)

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


memo = dict()
def sousa(V, hand, K):
  if K != 0:
    K -= 1
    if hand:
      yield 1 # sum(v for i, v in enumerate(hand) if i >= K or (i < K and v <= 0))
    if V:
      yield from sousa(V[1:], (hand + (V[0], )), K)
      yield from sousa(V[:-1], (hand +(V[-1], )), K)


# print(max(0, max(hand for hand in sousa(tuple(V), tuple(), K))))

ans = 0
for i in range(K):
  hand = V[:i]
  for j in range(K-i):
    if j != 0:
      x = hand + V[-j:]
    else:
      x = hand
    rest = K - i - j
    summ = sum(v for i, v in enumerate(sorted(x)) if i >= rest or v > 0)
    ans = max(ans, summ)
    # print(f"K={K}, i={i}, j={j}, rest={rest}, sum={summ}, x={x}")
print(ans)

Submission status: Wrong Answer

Solution code:
N, K = [int(_) for _ in input().split()]
V_lis = [int(_) for _ in input().split()]

point_lis = []

for k in range(1, K+1):
  
  val_lis = []
  point = 0
  
  for left_k in range(1, min(k+1, N+1)):
    val_lis = V_lis[:left_k-1]
    if left_k < k:
      val_lis += V_lis[-(k-left_k):]

    point = sum(val_lis)
    num_of_neg = [_ for _ in val_lis if _ < 0]
    num_of_neg.sort()
  
    diff = K - k + 1
    if diff >= len(num_of_neg):
      point -= sum(num_of_neg)
    elif diff > 0:
      for x in range(diff):
        point -= num_of_neg[-x]
      
    point_lis.append(point)
  
print(max(point_lis))

Submission status: Wrong Answer

Solution code:
import copy

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

def patterns(n):
    limit = pow(4, n)
    for val in range(limit):
        flags = '{0:b}'.format(val).zfill(n*2)
        yield [flags[x:x + 2] for x in range(0, len(flags), 2)]

def try_ope(vals, pattern):
    values = copy.deepcopy(vals)
    my = []
    for ope in pattern:
        if len(values) == 0 and (ope[0] == '0'):
            return None
        if len(my) == 0 and (ope[0] == '1'):
            return None
        if ope == '00':
            my.append(values.pop(0))
            my.sort()
        if ope == '01':
            my.append(values.pop(-1))
            my.sort()
        if ope == '10':
            values.insert(0, my.pop(0))
        if ope == '11':
            values.insert(-1, my.pop(0))
    return sum(my)

answer = 0
for pattern in list(patterns(K)):
    val = try_ope(V, pattern)
    if val is None:
        continue
    if val > answer:
        print(pattern)
        answer = val
print(answer)

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs,heapq as hq
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l():
	return list(map(int,input().split()))
def uy():
	return map(int,input().split())
def s(x):
	a = []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa == x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x):
	return " ".join(map(str,x))

n,m = uy()

a = l()

su = 0
for i in range(n+1):
	ll = max(i,n-(m - i))
	if i == 0:
		nn = n + 1
	else:
		nn = n
	for j in range(ll,n+1):
		q = []
		co = 0
		p = a[:i]
		pp = a[j:]
		for k in range(len(p)):
			if p[k] < 0:
				hq.heappush(q,p[k])
		for k in range(len(pp)):
			if pp[k] < 0:
				hq.heappush(q,pp[k])
		co += sum(p)
		co += sum(pp)
		q.sort()
		for k in range(min(len(q),j-ll)):
			co += abs(hq.heappop(q))
		su = max(su,co)
print(su)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

fin = sys.stdin.readline
N, K = [int(elem) for elem in fin().split()]

v_list = [int(elem) for elem in fin().split()]

sum_list = []

K = min(N, K)

for p in range(K+1):
    for left in range(K-p+1):
        for right in range(K-p-left+1):
            if (left + right) < p:
                continue
            each_v_list = v_list[:left] + list(deque(v_list, right))
            each_v_list = sorted(each_v_list)
            each_v_list = each_v_list[p:]
            each_sum = sum(each_v_list)
            sum_list.append(each_sum)
print(max(max(sum_list), 0))

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs,heapq as hq
sys.setrecursionlimit(100000)
Max = sys.maxsize
def l():
	return list(map(int,input().split()))
def uy():
	return map(int,input().split())
def s(x):
	a = []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa == x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x):
	return " ".join(map(str,x))

n,m = uy()

a = l()

su = 0
for i in range(n):
	ll = max(i,n-(m - i))
	if i == 0:
		nn = n + 1
	else:
		nn = n
	for j in range(ll,n+1):
		q = []
		co = 0
		p = a[:i]
		pp = a[j:]
		for k in range(len(p)):
			if p[k] < 0:
				hq.heappush(q,p[k])
		for k in range(len(pp)):
			if pp[k] < 0:
				hq.heappush(q,pp[k])
		co += sum(p)
		co += sum(pp)
		q.sort()
		for k in range(min(len(q),j-ll)):
			co += abs(hq.heappop(q))
		su = max(su,co)
print(su)

Submission status: Wrong Answer

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

# 何個捨てるか
ans = 0
for i in range(K):
    # 右から何個目まで取るか
    if K-i > N:
        pick = q
        pick = sorted(pick)
        ans = max(sum(pick[i:]),ans)        
    else:
        pick = q[:K-i]
        pick = sorted(pick)
        ans = max(sum(pick[i:]),ans)
        for j in range(min(N,K-i)):
            pick = []
            pick = q[:j]+q[-(K-i-j):]
            pick = sorted(pick)
            ans = max(sum(pick[i:]),ans)
print(ans)

Submission status: Wrong Answer

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

    m = 0
    for i in range(K):
        for j in range(K-i):
            if j == 0:
                a = V[:K-i]
            else:
                a = V[:K-i-j] + V[-j:]
            a.sort()
            s = sum(a[i:])
            if s > m:
                m = s

    for k in range(K):
        for j in range(k):
            if j == 0:
                a = V[:k]
            else:
                a = V[:k-j] + V[-j:]
            s = sum(a)
            if s > m:
                m = s

    print(m)

main()

Submission status: Wrong Answer

Solution code:
import math, string, itertools, fractions, heapq, collections, re, array, bisect, copy, functools, random
import sys
from collections import deque, defaultdict, Counter; from heapq import heappush, heappop
from itertools import permutations, combinations, product, accumulate, groupby
from bisect import bisect_left, bisect_right, insort_left, insort_right
from operator import itemgetter as ig
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20; INF = float("INF"); ans = 0; tmp = 0; ansli = []; tmpli = []; candili = []
eps = 1.0 / 10 ** 10; mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]; ddn = dd + [(-1, 1), (1, 1), (1, -1), (-1, -1)]; ddn9 = ddn + [(0, 0)]
"""for dx, dy in dd:
        nx = j + dx; ny = i + dy
            if 0 <= nx < w and 0 <= ny < h:"""
def wi(): return list(map(int, sys.stdin.readline().split()))
def wip(): return [int(x) - 1 for x in sys.stdin.readline().split()]#WideIntPoint
def ws(): return sys.stdin.readline().split()
def i(): return int(sys.stdin.readline())
def s(): return input()
def hi(n): return [i() for _ in range(n)]
def hs(n): return [s() for _ in range(n)]#HeightString
def mi(n): return [wi() for _ in range(n)]#MatrixInt
def mip(n): return [wip() for _ in range(n)]
def ms(n): return [ws() for _ in range(n)]

n, k = wi()
v = wi()
v = deque(v)
pq = []
po = 0
cnt = 0
qwerty = min(n, k + 1)
for i in range(qwerty):
    if i != 0:
        heappush(pq, v[i - 1])
    for j in range(qwerty - i):
        if j != 0:
            heappush(pq, v[-j])
        while k - i - j - cnt > 0:
            if pq != []:
                po = 0
                po = heappop(pq)
                if po < 0:
                    cnt += 1
                    tmpli.append(po)
                else:
                    heappush(pq, po)
                    cnt = 0
                    break
            else:
                break
        cnt = 0
        ans = max(ans, sum(pq))
        for bb in tmpli:
            heappush(pq, bb)
        tmpli = []
    pq = []
    for g in range(i + 1):
        if g != 0:
            heappush(pq, v[g - 1])

print(ans)

Submission status: Wrong Answer

Solution code:
# まず取り出しきっちゃってから捨てる
# 左右からいくつずつ取り出すか

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

max_value = 0 # 何もとらない

for L in range(N+1):
  for R in range(N+1):
    if L+R > K:
      break
    if L+R > N:
      break
    #get = V[:L] + V[-R:]
    get = V[:L].copy()
    if R > 0:
      get += V[-R:].copy()
    get.sort()
    rest = K - (L+R)
    minus = sum((1 if x < 0 else 0 for x in get))
    if minus > rest:
      value = sum(get[rest:])
    else:
      value = sum((x for x in get if x > 0))
    if value > max_value:
      max_value = value
    print(L,R,rest,get,value)
      
      
   
print(max_value)

Submission status: Wrong Answer

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

left = np.cumsum([0] + v)
right = np.cumsum([0] + v[::-1])

results = []
for backn in range(k + 1):
    at = k - backn

    t = min(n, at)
    # print('----', backn, t)
    for i in range(0, t + 1):
        for shift in range(i + 1):
            p = v[:t - shift] + v[n - shift:]
            # print(v[:t - shift], v[n - shift:])
            p.sort()
            value = sum(p[backn:])
            results.append(value)
print(max(results + [0]))

Submission status: Wrong Answer

Solution code:
import heapq


def main():
    N, K = map(int, input().split())
    V = list(map(int, input().split()))
    if N <= K:
        V.sort()
        total = sum(V)
        ans = max(total, 0)
        for i in range(min(K-N, N)):
            total -= V[i]
            ans = max(ans, total)
        print(ans)
    else:
        left = [0] * (K+1)
        right = [0] * (K+1)
        for i in range(K, 0, -1):
            lv = V[:i]
            rv = V[-i:]
            left[i] = sum(lv)
            right[i] = sum(rv)
            lheap = list(lv)
            rheap = list(rv)
            heapq.heapify(lheap)
            heapq.heapify(rheap)
            lmsum = 0
            rmsum = 0
            for j in range(1, i):
                if i+j > K:
                    continue
                lmsum += heapq.heappop(lheap)
                left[i+j] = max(left[i+j], left[i] - lmsum)
                rmsum += heapq.heappop(rheap)
                right[i+j] = max(right[i+j], right[i] - rmsum)
        ans = 0
        for i in range(K+1):
            ans = max(max(left[i], 0) + max(right[K-i], 0), ans)
        print(ans)


if __name__ == "__main__":
    main()