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: Time Limit Exceeded

Solution code:
import itertools
import copy


class Deque:
    def __init__(self, default_deque: list):
        self.in_hand = []
        self.deque = default_deque

    def operation(self, operation_type: str):
        if operation_type == "A":
            self.in_hand.append(self.deque[0])
            del self.deque[0]
        elif operation_type == "B":
            self.in_hand.append(self.deque[-1])
            del self.deque[-1]
        elif operation_type == "C":
            if min(self.in_hand) < 0:
                self.deque.insert(0, min(self.in_hand))
                _index = self.in_hand.index(min(self.in_hand))
                del self.in_hand[_index]
            else:
                raise Exception
        elif operation_type == "D":
            if min(self.in_hand) < 0:
                self.deque.append(min(self.in_hand))
                _index = self.in_hand.index(min(self.in_hand))
                del self.in_hand[_index]
            else:
                raise Exception


if __name__ == '__main__':
    max_repeat_count = int(input().split()[1])
    value_list = list(map(int, input().split()))
    point_list = []
    for repeat_count in range(max_repeat_count+1):
        operation_pattern_iter = itertools.product(["A", "B", "C", "D"], repeat=repeat_count)
        for operation_pattern in operation_pattern_iter:
            deque = Deque(copy.copy(value_list))
            for operation in operation_pattern:
                try:
                    deque.operation(operation)
                except:
                    break
            else:
                point_list.append(sum(deque.in_hand))

    print(max(point_list))

Submission status: Time Limit Exceeded

Solution code:
import itertools
import copy


class Deque:
    def __init__(self, default_deque: list):
        self.in_hand = []
        self.deque = default_deque

    def operation(self, operation_type: str):
        if operation_type == "A":
            self.in_hand.append(self.deque[0])
            del self.deque[0]
        elif operation_type == "B":
            self.in_hand.append(self.deque[-1])
            del self.deque[-1]
        elif operation_type == "C":
            self.deque.insert(0, min(self.in_hand))
            _index = self.in_hand.index(min(self.in_hand))
            del self.in_hand[_index]
        elif operation_type == "D":
            self.deque.append(min(self.in_hand))
            _index = self.in_hand.index(min(self.in_hand))
            del self.in_hand[_index]


if __name__ == '__main__':
    max_repeat_count = int(input().split()[1])
    value_list = list(map(int, input().split()))
    point_list = []
    for repeat_count in range(max_repeat_count+1):
        operation_pattern_iter = itertools.product(["A", "B", "C", "D"], repeat=repeat_count)
        for operation_pattern in operation_pattern_iter:
            deque = Deque(copy.copy(value_list))
            for operation in operation_pattern:
                try:
                    deque.operation(operation)
                except:
                    break
            else:
                point_list.append(sum(deque.in_hand))

    print(max(point_list))

Submission status: Time Limit Exceeded

Solution code:
import heapq
N, K = [int(_) for _ in input().split()]
V = [int(_) for _ in input().split()]
ans = 0
for il in range(min([N + 1, K + 1])):
    for ir in range(min([N + 1 - il, K + 1 - il])):
        for dl in range(il + 1):
            for dr in range(ir + 1):
                if il + ir + dl + dr > K:
                    continue
                HL = V[:il]
                HR = V[N - ir:N]
                heapq.heapify(HL)
                heapq.heapify(HR)
                value = 0
                for _ in range(dl):
                    v = heapq.heappop(HL)
                    if v >= 0:
                        value += v
                        break
                value += sum(HL)
                for _ in range(dr):
                    v = heapq.heappop(HR)
                    if v >= 0:
                        value += v
                        break
                value += sum(HR)
                ans = max([ans, value])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys, heapq, copy
from collections import deque
input = sys.stdin.readline
'''
allinputs = iter(input().splitlines())
input = lambda : next(allinputs)
#'''

N, K = map(int, input().split())
V_init = deque(map(int, input().split()))
max_score = 0
hands = [0] * K
heapq.heapify(hands)

for i_rget in range(K + 1):
	for i_lget in range(max(K - i_rget, 0) + 1):
		for i_del in range(max(K - i_rget - i_lget, 0) + 1):
			score = 0
			hands = [0] * K
			V = copy.copy(V_init)
			for i in range(i_rget + 1):
				if i > 0 and V:
					tmp = V.pop()					
					heapq.heappush(hands, tmp)
					score += tmp
				
			for i in range(i_lget + 1):
				if i > 0 and V:
					tmp = V.popleft()
					heapq.heappush(hands, tmp)
					score += tmp
			
			for i in range(i_del + 1):
				if i > 0:
					tmp = heapq.heappop(hands)
					score -= tmp
			
			if score > max_score:
				max_score = score

print(max_score)

Submission status: Time Limit Exceeded

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

from heapq import heappush, heappop
for i in range(1, k+1):
  for j in range(1, i+1):
    for k in range(0, j+1):
      minus = []
      l = min(n, k)
      r = min(n-l, j-l)
      cur = 0
      for ll in range(l):
        cur += v[ll]
        if v[ll]<0:
          heappush(minus, v[ll])
      for rr in range(r):
        cur += v[n-rr-1]
        if v[n-rr-1]<0:
          heappush(minus, v[n-rr-1])
      rm = i-l-r
      while rm>0 and len(minus)>=rm:
        rm -= 1
        t = heappop(minus)
        cur -= t
      ans = max(ans, cur)
print(ans)

Submission status: Time Limit Exceeded

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

class Money:
    def __init__(self):
        self.yen = 0
        self.red = []

    def value(self):
        return self.yen + sum(self.red)

    def add(self, yen):
        if yen >= 0:
            self.yen += yen
        else:
            self.red.append(yen)

    def remove(self, yen):
        if yen >= 0:
            self.yen -= yen
        else:
            self.red.remove(yen)

#mny = Money()
def get(cnt, mny, lstop, rstop):
    ans = mny.value()

    if cnt <= 0:
        return ans

    if len(V) > 0:

        if not lstop:
            w = V.popleft()
            mny.add(w)
            ans = max(ans, get(cnt-1, mny, lstop, rstop))
            mny.remove(w)
            V.appendleft(w)

        if not rstop:
            w = V.pop()
            mny.add(w)
            ans = max(ans, get(cnt-1, mny, True, rstop))
            mny.remove(w)
            V.append(w)

    if len(mny.red) > 0:
        w = min(mny.red)
        mny.red.remove(w)

        V.appendleft(w)
        ans = max(ans, get(cnt-1, mny, len(mny.red) and True, len(mny.red) and True))
        V.popleft()

        mny.red.append(w)    

    return ans

print(get(K, Money(), 0, 0))

Submission status: Time Limit Exceeded

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

class Money:
    def __init__(self):
        self.yen = 0
        self.red = []

    def value(self):
        return self.yen + sum(self.red)

    def add(self, yen):
        if yen >= 0:
            self.yen += yen
        else:
            self.red.append(yen)

    def remove(self, yen):
        if yen >= 0:
            self.yen -= yen
        else:
            self.red.remove(yen)

#mny = Money()
def get(cnt, mny, lstop, rstop):
    ans = mny.value()

    if cnt <= 0:
        return ans

    if len(V) > 0:

        if lstop == 0:
            w = V.popleft()
            mny.add(w)
            ans = max(ans, get(cnt-1, mny, lstop, rstop))
            mny.remove(w)
            V.appendleft(w)
        elif lstop > 0:
            lstop -= 1

        if rstop == 0:
            w = V.pop()
            mny.add(w)
            ans = max(ans, get(cnt-1, mny, -1, rstop))
            mny.remove(w)
            V.append(w)

    if len(mny.red) > 0:
        w = min(mny.red)
        mny.red.remove(w)

        V.appendleft(w)
        ans = max(ans, get(cnt-1, mny, -1, -1))
        V.popleft()

        V.append(w)
        ans = max(ans, get(cnt-1, mny, -1, -1))
        V.pop()

        mny.red.append(w)    

    return ans

print(get(K, Money(), 0, 0))

Submission status: Time Limit Exceeded

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

class Money:
    def __init__(self):
        self.yen = 0
        self.red = []

    def value(self):
        return self.yen + sum(self.red)

    def add(self, yen):
        if yen >= 0:
            self.yen += yen
        else:
            self.red.append(yen)

    def remove(self, yen):
        if yen >= 0:
            self.yen -= yen
        else:
            self.red.remove(yen)

#mny = Money()
def get(cnt, mny, lstop, rstop):
    ans = mny.value()

    if cnt <= 0:
        return ans

    if len(V) > 0:

        if lstop == 0:
            w = V.popleft()
            mny.add(w)
            ans = max(ans, get(cnt-1, mny, lstop, rstop))
            mny.remove(w)
            V.appendleft(w)
        elif lstop > 0:
            lstop -= 1

        if rstop == 0:
            w = V.pop()
            mny.add(w)
            ans = max(ans, get(cnt-1, mny, -1, rstop))
            mny.remove(w)
            V.append(w)

    if len(mny.red) > 0:
        w = min(mny.red)
        mny.red.remove(w)

        V.appendleft(w)
        ans = max(ans, get(cnt-1, mny, -1, rstop))
        V.popleft()

        V.append(w)
        ans = max(ans, get(cnt-1, mny, lstop, -1))
        V.pop()

        mny.red.append(w)    

    return ans

print(get(K, Money(), 0, 0))

Submission status: Time Limit Exceeded

Solution code:
N,K = map(int,input().split())
V = list(map(int,input().split()))
ans = 0
R = min(N,K)
def f(A,B):
  global ans,R,V,K
  if A+B>R:
    return
  v = V[0:A]+V[N-B:N]
  if A+B>0:
    v.sort()
    for i in range(min(A+B,K-A-B)):
      if v[i]<0:
        v[i]=0
    ans = max(ans,sum(v))
  f(A+1,B)
  f(A,B+1)
f(0,0)
print(ans)

Submission status: Time Limit Exceeded

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

def f(l,r,k):
  global N,K,V,ans
  R = min(N,K)
  if r-l<0 or k>R:
    return
  v = V[0:l]+V[r:N]
  if l-r!=N:
    n = len(v)
    kk = k
    v.sort()
    for i in range(n):
      if kk>=R:
        break
      if v[i]<=0:
        v[i]=0
        kk+=1
    ans = max(ans,sum(v))
  f(l+1,r,k+1)
  f(l,r-1,k+1)
f(0,N,0)
print(ans)

Submission status: Time Limit Exceeded

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

def f(l,r,k):
  global N,K,V,ans
  if r-l<0 or k>K:
    return
  v = V[0:l]+V[r:N]
  if l-r!=N:
    n = len(v)
    kk = k
    v.sort()
    for i in range(n):
      if kk>=K:
        break
      if v[i]<=0:
        v[i]=0
        kk+=1
    ans = max(ans,sum(v))
  if r==l:
    return
  f(l+1,r,k+1)
  f(l,r-1,k+1)
f(0,N,0)
print(ans)

Submission status: Time Limit Exceeded

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

def f(l,r,k):
  global N,K,V,ans
  if r-l<0 or k>K:
    return
  v = V[0:l]+V[r:N]
  if l-r!=N:
    n = len(v)
    kk = k
    v.sort()
    for i in range(n):
      if kk>=K:
        break
      if v[i]<=0:
        v[i]=0
        kk+=1
    ans = max(ans,sum(v))
  f(l+1,r,k+1)
  f(l,r-1,k+1)
f(0,N,0)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
from collections import deque

def state_brute_force(state, count):
    state_list = [state for _ in range(count)]
    for s in product(*state_list):
        yield s


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

ans = 0

pop_l = deque.popleft
pop_r = deque.pop
add_l = deque.appendleft
add_r = deque.append

stop_condition = sum([item for item in D if item > 0])
if stop_condition > 0:
    for cmb in state_brute_force([pop_l, pop_r, add_l, add_r], K):
        q = deque(D)
        now = []
        value = 0
        for operation in cmb:
            if operation == add_l or operation == add_r:
                if len(now) == 0:
                    break
                item = min(now)
                now.remove(item)
                operation(q, item)
            if operation == pop_l or operation == pop_r:
                if len(q) == 0:
                    break
                now.append(operation(q))
        value = max(value, sum(now))
        ans = max(ans, value)
        if ans == stop_condition:
            break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
from collections import deque
from copy import deepcopy

def state_brute_force(state, count):
    state_list = [state for _ in range(count)]
    for s in product(*state_list):
        yield s


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

ans = 0

pop_l = deque.popleft
pop_r = deque.pop
add_l = deque.appendleft
add_r = deque.append

stop_condition = sum([item for item in D if item > 0])

cache = {}

for cmb in state_brute_force([pop_l, pop_r, add_l, add_r], K):
    q = deque(D)
    now = []
    op_counter = 0
    value = 0
    operations = []
    for operation in cmb:
        operations.append(operation)
        ca = cache.get(tuple(operations))
        if ca is not None:
            q = deque(ca[0])
            now = deepcopy(ca[1])
            continue
        if operation == add_l or operation == add_r:
            if len(now) == 0:
                break
            item = min(now)
            now.remove(item)
            operation(q, item)
        if operation == pop_l or operation == pop_r:
            if len(q) == 0:
                break
            now.append(operation(q))
    cache[tuple(operations)] = (list(q), now)
    value = max(value, sum(now))
    ans = max(ans, value)
    if ans == stop_condition:
        break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
from collections import deque

def state_brute_force(state, count):
    state_list = [state for _ in range(count)]
    for s in product(*state_list):
        yield s


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

ans = 0

pop_l = deque.popleft
pop_r = deque.pop
add_l = deque.appendleft
add_r = deque.append

stop_condition = sum([item for item in D if item > 0])

for cmb in state_brute_force([pop_l, pop_r, add_l, add_r], K):
    q = deque(D)
    now = []
    value = 0
    for operation in cmb:
        if operation == add_l or operation == add_r:
            if len(now) == 0:
                break
            item = min(now)
            now.remove(item)
            operation(q, item)
        if operation == pop_l or operation == pop_r:
            if len(q) == 0:
                break
            now.append(operation(q))
    value = max(value, sum(now))
    ans = max(ans, value)
    if ans == stop_condition:
        break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
from collections import deque

def state_brute_force(state, count):
    state_list = [state for _ in range(count)]
    for s in product(*state_list):
        yield s


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

ans = 0

pop_l = deque.popleft
pop_r = deque.pop
add_l = deque.appendleft
add_r = deque.append

stop_condition = sum([item for item in D if item > 0])

for cmb in state_brute_force([pop_l, pop_r, add_l, add_r], K):
    q = deque(D)
    now = []
    value = 0
    for operation in cmb:
        if operation == add_l or operation == add_r:
            if len(now) == 0:
                break
            item = min(now)
            now.remove(item)
            operation(q, item)
        if operation == pop_l or operation == pop_r:
            if len(q) == 0:
                break
            now.append(operation(q))
        value = max(value, sum(now))
    ans = max(ans, value)
    if ans == stop_condition:
        break

print(ans)

Submission status: Time Limit Exceeded

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 (tuple(v_list.tolist()), tuple(hand.tolist()), k + 2) in memo:
        # print('hit')
        return -10 ** 7 * 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_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)
    # hand = []

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

Submission status: Time Limit Exceeded

Solution code:
import copy

def Base_10_to_n(X, n):
    if (int(X/n)):
        return Base_10_to_n(int(X/n), n)+str(X%n)
    return str(X%n)

def hokan(str,n):
    if len(str) < n:
        str = "0" * (n- len(str)) + str
    return str

n, k = map(int,input().split())
db = [int(i) for i in input().split()]
hk = []

for i in range(4**k):
    h = []
    d = copy.deepcopy(db)
    st = Base_10_to_n(i,4)
    st = hokan(st,k)
    while st:
        r = int(st[0])
        st = st[1:]
        if r == 0 and d:
            h.append(d.pop(0))
        elif r == 1 and d:
            h.append(d.pop(-1))
        elif r == 2 and h:
            h.sort()
            d = [h.pop(0)] + d
        elif r == 3 and h:
            h.sort()
            d.append(h.pop(0))
    hk.append(sum(h))
print(max(hk))

Submission status: Time Limit Exceeded

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_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)
    # hand = []

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

Submission status: Time Limit Exceeded

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

def rec(k, d, h, mod):
    if not d or k == 0:
        return sum(h)

    if mod == 1:
        h.append(d.pop(0))
    elif mod == 2:
        h.append(d.pop(-1))
    elif mod == 3 and h:
        d.append(min(h))
        h.remove(min(h))
    elif mod == 4 and h:
        d.insert(0, min(h))
        h.remove(min(h))

    m = max(rec(k - 1, d.copy(), h.copy(), i) for i in range(1, 6))
    return m

print(max(rec(K, D[:], [], i) for i in range(1, 6)))

Submission status: Time Limit Exceeded

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

Q = [ [0 for _ in range(N + 2 * K)] for _ in range(K+1) ]

S = K
E = K + N

for i in range(K, K+N):
    Q[0][i] = V[i-K]

def get(i, S, E, hav, yen):

    ans = yen

    if i >= K:
        return yen

    if S < E:    
        for j in range(S,E):
            Q[i+1][j] = Q[i][j]
        nhav = hav.copy()
        w = Q[i][S]
        nhav.append(w)
        ans = max(ans, get(i+1, S+1, E, nhav, yen + w))

        for j in range(S,E):
            Q[i+1][j] = Q[i][j]
        nhav = hav.copy()
        w = Q[i][E-1]
        nhav.append(w)
        ans = max(ans, get(i+1, S, E-1, nhav, yen + w))

    if len(hav) > 0:
        w = min(hav)

        for j in range(S,E):
            Q[i+1][j] = Q[i][j]
        nhav = hav.copy()
        nhav.remove(w)
        Q[i+1][E] = w
        ans = max(ans, get(i+1, S, E+1, nhav, yen - w))

        for j in range(S,E):
            Q[i+1][j] = Q[i][j]
        nhav = hav.copy()
        nhav.remove(w)
        Q[i+1][S-1] = w
        ans = max(ans, get(i+1, S-1, E, nhav, yen - w))
    
    return ans

print(get(0, S, E, [], 0))

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop, heapify

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

# N jewels in dequeue D
# at most K operations
# 1 <= N <= 50
# 1 <= K <= 100
# -10000000 <= Vi <= 10000000

# Operation A, B: Remove left or right
# Operation C, D: Add to left or right

S = 0
for take in range(K + 1):
    for takeL in range(take + 1):
        for takeR in range(take - takeL + 1):
            hand = []
            for i in range(takeL):
                if i >= len(V):
                    break
                heappush(hand, V[i])
            for i in range(takeR):
                if N - i - 1 < takeL:
                    break
                heappush(hand, V[N- i - 1])
            S = max(sum(hand), S)
            for _ in range(K - take):
                if not hand or hand[0] >= 0:
                    break
                heappop(hand)
                S = max(sum(hand), S)
print(S)