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.

Solution (Python):

import numpy as np

N,K = map(int,raw_input().split())

V = map(int,raw_input().split())
V = np.array(V)
ans = 0

for l in xrange(K+1):
    for m in xrange(K+1-l):
        if (l+m) > N:
            continue
        d = K-l-m
        now = 0
        s = np.array([])
        for i in xrange(l):
            now += V[i]
            s = np.append(s,V[i])
        for i in xrange(m):
            now += V[N-i-1]
            s = np.append(s,V[N-i-1])
        s = np.sort(s)
        for i in xrange(d):
            if i>=s.size:
                break
            if s[i]>0:
                break
            now -= s[i]
        
        if ans < now:
            ans = now

print int(ans)

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

for left in range(max_loop + 1):
    for right in range(max_loop - left + 1):
        tmp = v[:left] + v[n-right:]
        m = sorted(filter(lambda x: x< 0, tmp))[:k - left - right]
        ans = max(ans, sum(tmp) - sum(m))
print(ans)

Solution (Python):
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):
        li = v[:a]
        if b > 0:
            li += v[-b:]
        li.sort()
        count = 0
        while (a + b + count < k):
            if len(li) > 0 and li[0] < 0:
                count += 1
                li = li[1:]
            else:
                break
        ans = max(ans, sum(li))

print(ans)

Solution (Python):
N,K=map(int,input().split())
V=list(map(int,input().split()))
R=min(N,K)
M=0
for a in range(0,R+1):
    for b in range(0,R-a+1):
        left=V[0:a]
        right=V[N-b:N]
        getV=sorted(left+right)
        for k in range(K-(a+b)):
            if getV!=[] and getV[0]<0:
                getV=getV[1:]
        sumGetV=sum(getV)
        if sumGetV>M:
            M=sumGetV
print(M)

Solution (Python):
n,k = map(int,input().split())
List = list(map(int,input().split()))

ans=0

for i in range(k+1):
    for j in range(k-i+1):
        Hand = []
        if i+j>n:
            break
        Hand=List[:i]
        Hand.extend(List[n-j:])
        tmp=sum(Hand)
        
        Hand.sort()
        
        for l in range(min(k-i-j,i+j)):
            if Hand[l]>=0:
                break
            tmp -= Hand[l]
        ans = max(ans,tmp)
        
print(ans)

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





ans = 0

for k_i in range(min(2*n+1,k+1)):
  
  
  rem_min = 0
  if k_i > n:
    rem_min = k_i - n
  for rem in range(rem_min, k_i//2+1):
    
    for j in range(k_i-rem+1):
      
      hand_tmp = v[:j] + v[::-1][:k_i-rem-j]
      hand_tmp.sort()
      
      
      hand_tmp = hand_tmp[rem:]
      ans_tmp = sum(hand_tmp)
      if ans_tmp > ans:
        ans = ans_tmp
        
print(ans)

Solution (Python):
N,K=map(int, raw_input().split())
V=map(int, raw_input().split())

max_len=min(N,K)

ans=0
for l in range(max_len+1):
	for r in range(max_len-l+1):
		T=V[:l]
		if r!=0:	T+=V[-1*r:]
		suteru=K-(l+r)
		
		T.sort()

		for i in range( min( suteru, len(T)) ):
			if T[i]<0:
				T[i]=0
		ans=max( ans, sum(T) )

print ans

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

for left in range(k + 1):
    for right in range(k - left + 1):
        if left + right > n:
            break
        hold = []
        hold.extend(v[:left])
        hold.extend(v[n-right:])
        hold.sort()
        total = sum(hold)
        for i in range(min(k - left - right, left + right)):
            if 0 <= hold[i]:
                break
            total -= hold[i]
        M = max(M, total)

print(M)

Solution (Python):


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

VN = [0] + VN + [0]

score_a = 0
neg_l = []

ans = 0
for a in range(len(VN)):
    l = VN[a]
    score_a += l
    if l < 0:
        neg_l.append(l)

    score_b = 0
    neg_r = []
    for b in range(len(VN)):
        r = VN[N + 1 - b]
        score_b += r
        if r < 0:
            neg_r.append(r)

        if a + b > K or a + b > N:
            break
        else:
            negs = neg_l + neg_r
            negs.sort()
            score_cd = sum(negs[:min(len(negs), K - a - b)])
            score = score_a + score_b - score_cd
            ans = max(ans, score)
print(ans)

Solution (Python):
n,k=map(int,input().split())
v=list(map(int,input().split()))
 
ans=0
 
for a in range(50):
  for b in range(50):
    if a+b <= min(n,k):
      li=v[:a]+v[n-b:]
      sumv = sum(li)
      li.sort()
      for i in range(min(k-a-b,len(li))):
        if li[i] < 0:
          li[i] = 0
        else:
          break
      ans=max(ans,sum(li))
      
print(ans)

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

for a in range(50):
    for b in range(50):
        if a + b <= min(n,k):
            li = liv[:a] + liv[n-b:]
            sum1 = sum(li)
            li.sort()
            for i in range(min(k-a-b,len(li))):
                if li[i] < 0:
                    li[i] = 0
                else:
                    break
            ans = max(ans,sum(li))

print(ans)

Solution (Python):

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

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



ans = 0


for n in range(1, min(K, N)+1):
    
    m = min(K-n, n)
    for l in range(n+1):
        
        r = n-l
        
        S = V[:l] + (V[-r:] if r != 0 else [])
        
        S.sort()

        an = 0
        for i, a in enumerate(S):
            if i < m and a < 0:
                continue
            else:
                an += a
        ans = max(ans, an)

print(ans)

Solution (Python):
N, K = map(int, input().split())
V = [int(i) for i in input().split()]

ans = 0
R = min(N, K)
for i in range(R + 1):
    for j in range(R - i + 1):
        A = []
        A += V[: i]
        if j > 0:
            A += V[- j :]
        A.sort()
        A2 = A[: K - (i + j)]
        for a in A2:
            if a < 0:
                A.remove(a)
        tmp = sum(A)
        ans = max(ans, tmp)
                
print(ans)

Solution (Python):




import collections
import itertools

def find_index(iterable, func):
    i = 0
    for it in iterable:
        if func(it):
            break
        i += 1
    return i

def slice_deq(deq, n):
    return itertools.islice(deq, 0, n)

def main():
    
    n, k = [int(s) for s in input().split()]
    vs = (int(s) for s in input().split())
    
    vs = collections.deque(vs)
    R = min(n, k)
    def gene_tv():
        for i in range(1, R+1):
            vs.rotate(-1)
            vs.reverse()
            for _ in range(i+1):
                temp = list(slice_deq(vs, i))
                temp.sort()
                l = find_index(temp, lambda x: x>0)
                l = min(l, k-i)
                yield sum(temp[l:])
                vs.rotate(-1)
            vs.rotate(-(i-1))
    ans = max(gene_tv())
    ans = max(ans, 0)
    
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):




import collections

def find_index(iterable, func):
    i = 0
    for it in iterable:
        if func(it):
            break
        i += 1
    return i

def main():
    
    n, k = [int(s) for s in input().split()]
    vs = [int(s) for s in input().split()]
    
    R = min(n, k)
    def gene_lr():
        for i in range(1, R+1):
            for j in range(i+1):
                yield(i-j, j)
    def gene_tv():
        for l, r in gene_lr():
            tv = 0
            temp = vs[:l] + vs[n-r:]
            temp.sort()
            i = find_index(temp, lambda x: x>0)
            s = k-(l+r)
            s = min(i, s)
            yield sum(temp[s:])
    ans = max(gene_tv())
    ans = max(ans, 0)
    
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):




import collections
import itertools

def slice_deq(deq, n):
    return itertools.islice(deq, 0, n)

def main():
    
    n, k = [int(s) for s in input().split()]
    vs = (int(s) for s in input().split())
    
    vs = collections.deque(vs)
    R = min(n, k)
    def gene_tv():
        for i in range(1, R+1):
            vs.rotate(-1)
            vs.reverse()
            for _ in range(i+1):
                tv = 0
                pps = []
                for v in slice_deq(vs, i):
                    tv += v
                    if v<0:
                        pps.append(v)
                
                vs.rotate(-1)
                pps.sort()
                pp = sum(pps[:k-i])
                yield tv-pp
            vs.rotate(-(i-1))
    ans = max(gene_tv())
    ans = max(ans, 0)
    
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):




def get_right(l, r):
    return l[-r:] if r!=0 else []

def main():
    
    n, k = [int(s) for s in input().split()]
    vs = [int(s) for s in input().split()]
    
    R = min(n, k)
    def gene_lr():
        for i in range(1, R+1):
            for j in range(i+1):
                yield(i-j, j)
    def gene_tv():
        for l, r in gene_lr():
            tv = 0
            pps = []
            for v in vs[:l] + vs[n-r:]:
                tv += v
                if v<0:
                    pps.append(v)
            s = k-(l+r)
            pps.sort()
            yield tv-sum(pps[:s])
    ans = max(gene_tv())
    
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
import sys


s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in ss]
ss2nnn = lambda ss: [s2nn(s) for s in ss]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline().rstrip() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

def main():
    N, K = i2nn()
    V = i2nn()
    n = 0
    for l in range(K+1):
        for r in range(K+1-l):
            if l + r > N:
                continue
            v = V[:l]
            if r > 0:
                v += V[-r:]
            vp = []
            vn = []
            for t in v:
                if t > 0:
                    vp.append(t)
                elif t < 0:
                    vn.append(t)
            vn.sort()
            k = K-l-r
            n2 = sum(vn[k:]) + sum(vp)
            if n < n2:
                n = n2
    print(n)

main()

Solution (Python):
N, K = map(int, input().split())
v = list(map(int, input().split()))

max_pick = min(K, N)
ans = 0



for left in range(max_pick + 1):
    for right in range(max_pick - left + 1):
        t = v[:left] + v[N - right:]
        m = sorted(filter(lambda x: x < 0, t))[:K - left - right]
        ans = max(ans, sum(t) - sum(m))
print(ans)

Solution (Python):
import itertools
import copy


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

    def operation(self, operation_type: str):
        if operation_type == "A":
            self.in_hand.append(self.deque[0])
            del self.deque[0]
            self.operation_count += 1
        elif operation_type == "B":
            self.in_hand.append(self.deque[-1])
            del self.deque[-1]
            self.operation_count += 1
        elif operation_type == "C":
            self.in_hand.sort()
            for i in range(self.max_count - self.operation_count):
                if self.in_hand[0] < 0:
                    del self.in_hand[0]
                else:
                    return


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.combinations_with_replacement(["A", "B"], repeat_count)
        for operation_pattern in operation_pattern_iter:
            deque = Deque(copy.copy(value_list), max_repeat_count)
            for operation in operation_pattern:
                try:
                    deque.operation(operation)
                except:
                    break
            else:
                try:
                    deque.operation("C")
                    point_list.append(sum(deque.in_hand))
                except:
                    point_list.append(sum(deque.in_hand))
                    break
    print(max(point_list))

Solution (Python):

import sys
from heapq import heapify, heappop

def solve(N: int, K: int, V: "List[int]"):
    ans = 0
    for n_all in range(min(N, K)+1):
        for n_l in range(n_all+1):
            n_r = n_all - n_l
            tmp_v = V[:n_l] + V[N-n_r:]
            heapify(tmp_v)
            i = 0
            while len(tmp_v) > 0 and tmp_v[0] < 0 and i < K-n_all:
                _ = heappop(tmp_v)
                i += 1
            ans = max(ans, sum(tmp_v))
    print(ans)
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    K = int(next(tokens))  
    V = [ int(next(tokens)) for _ in range(N) ]  
    solve(N, K, V)

if __name__ == '__main__':
    main()

Solution (Python):

import sys


def solve(N: int, K: int, V: "List[int]"):
    ans = 0
    for n_all in range(min(N, K)+1):
        for n_l in range(n_all+1):
            n_r = n_all - n_l
            tmp_v = sorted(V[:n_l] + V[N-n_r:])
            n_neg = sum([e < 0 for e in tmp_v])
            ans = max(ans, sum(tmp_v[min(n_neg, K-n_all):]))
    print(ans)

    return



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    K = int(next(tokens))  
    V = [ int(next(tokens)) for _ in range(N) ]  
    solve(N, K, V)

if __name__ == '__main__':
    main()

Solution (Python):


n, k = list(map(int, input().split() ))
values = a = list(map(int, input().split() ))
ans = 0

left_pop_max = min(k, n)
for left in range(left_pop_max+1):
	picked_l = values[:left]

	
	right_pop_max = left_pop_max - left
	for right in range(right_pop_max+1):
		
		if (right > 0):
			picked = picked_l + values[-right:]
		else:
			picked = picked_l

		picked.sort()
		push_max = min(k - left - right, left + right)
		push_val_sum = 0
		for i in range(push_max):
			if picked[i] >= 0:
				break
			push_val_sum += picked[i]

		new_ans = sum(picked) - push_val_sum
		ans = max(ans, new_ans)

print(ans)

Solution (Python):
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):
        take_list = []
        for k in range(j):
            take_list.append(V[k])
        for k in range(1, i-j+1):
            take_list.append(V[-k])
        take_list.sort()
        for l in range(K-i):
            if len(take_list) >= 1:
                if take_list[0] < 0:
                    take_list.pop(0)
                else:
                    break
        ans = max(ans, sum(take_list))

print(ans)

Solution (Python):
n, k = [int(i) for i in input().split()]
V = [int(i) for i in input().split()]

ans = 0

for m in range(min(n, k) + 1):
    for left in range(m + 1):
        right = m - left
        H = V[:left] + V[n - right:]
        H.sort()
        S = sum(H)
        remain = k - m
        for i in range(min(m, remain)):
            if H[i] > 0:
                break
            S -= H[i]
        
        ans = max(ans, S)

print(ans)

Solution (Python):
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) + 1):
        for right in range(min(N, K) - left + 1):
            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())

Solution (Python):
import bisect

N, K = list(map(int, input().split()))
V = list(map(int, input().split()))
ans = 0
n = min(N, K)
for A in range(n+1):
    for B in range(n-A+1):
        if not A and not B:
            continue
        if not A:
            AB = V[-B:]
        elif not B:
            AB = V[:A]
        else:
            AB = V[:A] + V[-B:]

        AB.sort()
        idx = bisect.bisect_left(AB, 0)
        k = K - (A + B)
        ans = max(ans, sum(AB[min(k, idx):]))

print(ans)

Solution (Python):
def calc_score(cnt_left, cnt_right, cnt_back, deq):
  got = deq[0:cnt_left]
  got.extend(deq[len(deq) - cnt_right:])
  sort = sorted(got)
  score = sum(sort[cnt_back:])
  return score

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

  deq = [int(v) for v in input().split()]

  high_score = 0
  for cnt_act in range(max_act + 1):
    for cnt_get in range(cnt_act + 1):
      
      
      if cnt_get > len(deq):
        break
        
      
      cnt_back = cnt_act - cnt_get
      
      if cnt_back >= cnt_get:
        continue
        
      
      for cnt_get_left in range(cnt_get + 1):
        cnt_get_right = cnt_get - cnt_get_left
        score = calc_score(cnt_get_left, cnt_get_right, cnt_back, deq)
        high_score = max(high_score, score)
       
  print(high_score)
  
main()

Solution (Python):
n,k = map(int,input().split())
v = list(map(int,input().split()))
kk = k
k = min(n,k)

ans = 0
for i in range(k+1):
	for j in range(k-i+1):
		
		L = v[:i]
		R = v[-j:]
		if len(R) == n:
			R = []
		LR = L+R+[0]
		LR.sort()
		zero_idx = min(LR.index(0),kk-i-j)
		
		ans = max(ans,sum(LR[zero_idx:]))
print(ans)

Solution (Python):
import sys
import collections
import copy


scan = sys.stdin.readline


def main():
    n, k = map(int, scan().rstrip().split())
    values = collections.deque([int(value) for value in scan().rstrip().split()])

    results = []

    for a in range(min(n, k) + 1):
        for b in range(min(n, k) - a + 1):
            hands = [0] * n
            v = copy.deepcopy(values)

            for _ in range(a):
                hands.append(v.popleft())
            for _ in range(b):
                hands.append(v.pop())

            hands.sort()

            c_d = 0
            for c_d in range(k - a - b):
                if hands[c_d] < 0:
                    hands[c_d] = 0
                else:
                    break
            results.append(sum(hands))
            hands = [0] * n

    results.sort(reverse=True)
    print(results[0])


if __name__ == '__main__':
    main()

Solution (Python):
import heapq
from collections import deque
n,k = map(int,input().split())
v=list(map(int,input().split()))
 
res = 0 
for i in range(k+1): 
    for j in range(k+1-i): 
        d = deque(v) 
        num = 0 
        a = [] 
 
        cnt = 0 
        while cnt<i and len(d):
            x = d.popleft() 
            heapq.heappush(a,x) 
            num += x 
            cnt += 1
        cnt = 0
        while cnt<j and len(d):
            x = d.pop()
            heapq.heappush(a,x)
            num += x
            cnt += 1
 
        sub = k-i-j 
        while sub > 0 and len(a): 
            y = heapq.heappop(a) 
            if y <= 0: 
                num -= y 
            sub -= 1
        
        res = max(res,num)
print(res)

Solution (Python):
import heapq
from collections import deque

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

res = 0 
for i in range(K+1): 
    for j in range(K+1-i): 
        sub = K - i - j 
        d = deque(v) 
        a = [] 
        
        
        cnt = 0
        while (cnt < i) & (len(d) > 0):
            heapq.heappush(a, d.popleft())
            cnt += 1
            
        
        cnt = 0
        while (cnt < j) & (len(d) > 0):
            heapq.heappush(a, d.pop())
            cnt += 1
        
        
        
        b = 0 
        cnt = 0
        while (cnt < sub) & (b <= 0) & (len(a) > 0):
            b = heapq.heappop(a)
            cnt += 1
        value = sum(a) + b if b > 0 else sum(a)
        res = max(res, value)
print(res)

Solution (Python):
N , K = map(int , input().split())

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

ans = 0
try_num = min(N,K)
for i in range(1 , try_num + 1):
    for j in range(i+1):
        pick_list = V[:i-j] + V[N - j:]
        
        rest_try_num = min(K-i , i)
        pick_list = sorted(pick_list) 
        for k in range(rest_try_num):
            if pick_list[k] <0:
                pick_list[k] = 0
            else:
                break

        ans = max(ans , sum(pick_list))

print(ans)

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

idou=min(n,k)
ans=0

for i in range(idou):
    for j in range(n,n-idou+i,-1):

        A=v[:i+1]
        B=v[j:]
        C=[0 for i in range(k)]
        C+=A+B
        C.sort()
        C=[C[i] for i in range(k-len(A)-len(B))if 0>C[i]]

        

        ans=max(sum(A)+sum(B)-sum(C),ans)

ans=max(sum(v[n-k:]),ans)


print(ans)

Solution (Python):
n,k = map(int, input().split())
list_v = list(map(int, input().split()))

retn = 0

k_cap = k
if (k > n):
    k_cap = n

for l in range(k_cap + 1):
    list_mine_l = list_v[:l]

    for r in range(k_cap - l + 1):
        list_mine_r = list_mine_l.copy()
        if (r > 0):
            list_mine_r.extend(list_v[-r:])
        list_mine_r.sort()

        sss = len(list_mine_r)
        if (sss > k-l-r):
            sss = k-l-r
        for s in range(sss + 1):
            list_mine_s = list_mine_r[s:]

            if (len(list_mine_s) > 0):
                tmp = sum(list_mine_s)
                if (retn < tmp):
                    retn = tmp

print(retn)

Solution (Python):
from collections import deque
n,k=map(int,input().split())
v=[int(_) for _ in input().split()]
num=min(n,k)
fans=0
for lll in range(num+1):
  for rrr in range(num-lll+1):
    rest=k-lll-rrr
    if rrr!=0:
      pick=v[:lll]+v[-rrr:]
    else:
      pick=v[:lll]
    ans=sum(pick)
    pick=sorted(pick)
    for iii in range(min(rest,len(pick))):
      if pick[iii]<0:
        ans-=pick[iii]
    fans=max(ans,fans)
print(fans)

Solution (Python):



def main():
    n, k = map(int, input().split())
    v = list(map(int, input().split()))
    reverse_v = v[::-1]
    ans = 0

    
    
    for left in range(k + 1):
        for right in range(k - left + 1):
            if left + right > n:
                continue

            remain = k - (left + right)
            merged_v = sorted(v[:left] + reverse_v[:right])
            merged_v_len = len(merged_v)
            minus = 0

            for i in range(min(remain, merged_v_len)):
                if merged_v[i] < 0:
                    minus += merged_v[i]

            ans = max(ans, sum(merged_v) - minus)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):



def main():
    n, k = map(int, input().split())
    v = list(map(int, input().split()))
    reverse_v = v[::-1]
    ans = 0

    for left in range(k + 1):
        for right in range(k - left + 1):
            if left + right > n:
                continue

            remain = k - (left + right)
            merged_v = sorted(v[:left] + reverse_v[:right])
            merged_v_len = len(merged_v)
            minus = 0

            for i in range(min(remain, merged_v_len)):
                if merged_v[i] < 0:
                    minus += merged_v[i]

            ans = max(ans, sum(merged_v) - minus)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import heapq
N, K = [int(_) for _ in input().split()]
V = [int(_) for _ in input().split()]
ans = 0
for il in range(K + 1):
    for ir in range(K + 1 - il):
        if il + ir > min([N, K]):
            continue
        H = V[:il] + V[N - ir:N]
        heapq.heapify(H)
        now = 0
        for d in range(1, il + ir):
            if il + ir + d > K:
                break
            v = heapq.heappop(H)
            if v >= 0:
                now += v
                break
        now += sum(H)
        ans = max([ans, now])
print(ans)

Solution (Python):

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

ans = 0
for sublen in range(1, min(k+1,n+1)):

    for left in range(0, sublen+1):
        right = sublen - left
        subq = vl[:left] + vl[n-right:]
        subq.sort()

        rlen_max = min(k-sublen, len(subq)-1 )
        rlenf = 0
        for rlen in range(rlen_max-1, -1, -1):
            if subq[rlen] <= 0:
                rlenf = rlen + 1
                break

        ans = max(ans, sum(subq[rlenf:]))


print(ans)

Solution (Python):


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

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

ans = 0  



for pick in range(min(K+1, N+1)):
    
    for right in range(pick+1):
        left = pick-right  
        pick_list = V[:right]+V[N-left:]

        
        pick_list = sorted(pick_list)
        tmp_ans = sum(pick_list)  
        rem = min(K-pick, len(pick_list))  
        for i in range(rem):  
            if pick_list[i] < 0:
                tmp_ans -= pick_list[i]
            else:
                break
        ans = max(tmp_ans, ans)
print(ans)

Solution (Python):


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

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

ans = 0
for pick in range(min(K+1, N+1)):
    for right in range(pick+1):
        left = pick-right
        tmp_list = V[:right]+V[N-left:]
        tmp_list = sorted(tmp_list)
        tmp_ans = sum(tmp_list)
        rem = min(K-pick, len(tmp_list))
        for i in range(rem):
            if tmp_list[i] < 0:
                tmp_ans -= tmp_list[i]
            else:
                break
        ans = max(tmp_ans, ans)
print(ans)

Solution (Python):
import sys, os

f = lambda:list(map(int,input().split()))
if 'local' in os.environ :
    sys.stdin = open('./input.txt', 'r')

def solve():
    n, k = f()
    v = f()

    ans = 0
    for take in range(1, min(k+1, n+1)):
        r_op = k - take
        for left in range(0, take+1):
            right = take - left
            nums = v[:left] + v[n- right:]
            nums = sorted(nums)
            cur_ans = sum(nums) 

            for i in range(r_op):
                if i<len(nums) and nums[i]<0:
                    cur_ans += abs(nums[i])

            ans = max(ans, cur_ans)
    
    print(ans)

            


solve()

Solution (Python):
N,K = (int(i) for i in input().split())
V = [int(i) for i in input().split()]
dashi = min([N,K])
result2 = 0
for i in range(dashi + 1):
    modoseru = K - i
    for leftdashi in range(i + 1):
        values = [0]
        for k in range(leftdashi):
            values.append(V[k])
        for J in range(i - leftdashi):
            if J >= 0:
                values.append(V[-1 * J - 1])

        values.sort()
        for n in range(modoseru):
            if len(values) >= 1 and values[0] <= 0:
                values.pop(0)
        result = sum(values)
        if result2 < result:
            result2 = result
            
print(result2)

Solution (Python):
def smaller(x, y):
	if x < y: return x
	return y

N, K = map(int, input().split())
V = list(map(int, input().split()))
M = smaller(N, K)
max = 0
for i in range(0, M+1):
	for j in range(0, M+1-i):
		negative = []
		sum = 0
		for k in range(0, i):
			if V[k] < 0: negative.append(V[k])
			sum += V[k]
		for k in range(0, j):
			if V[-1-k] < 0: negative.append(V[-1-k])
			sum += V[-1-k]
		negative.sort()
		for k in range(0, smaller(len(negative), K-i-j)):
			sum -= negative[k]
		if max < sum: max = sum
print(max)

Solution (Python):
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):
		tmp = 0
		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(max(K - i_rget - i_lget, 0) + 1):
			if i > 0:
				tmp = heapq.heappop(hands)
				if tmp < 0:
					score -= tmp
				else:
					break
		
		if score > max_score:
			max_score = score

print(max_score)

Solution (Python):
N, K = map(int, input().split())
V = list(map(int, input().split()))
k = min(N, K)
v = 0
for i in range(k + 1):
    for j in range(k - i + 1):
        v_tmp = V[:i] + V[(N - j):]
        v_tmp.sort()
        for l in range(K - (i + j) + 1):
            v = max(v, sum(v_tmp[l:]))
print(v)

Solution (Python):
N, K = map(int, input().split())
V = list(map(int, input().split()))
k = min(N,K)
v = 0
for i in range(k  + 1):
    for j in range(k  - i + 1):
        v_tmp = V[:i] + V[(N - j):]
        v_tmp.sort()
        for l in range(K - (i + j) + 1):
            v = max(v, sum(v_tmp[l:]))
print(v)