We need to solve a problem: given a dequeue (double-ended queue) of N jewels with values V_i. We can perform at most K operations. Operations: A: take leftmost from D to hand; B: take rightmost from D to hand; C: put a jewel from hand to left end of D; D: put a jewel from hand to right end of D. We start with empty hand. At the end, we care about sum of values of jewels in hand. We want maximize that sum.
We can perform up to K operations. Each operation either takes a jewel from D to hand (increasing hand count, decreasing D) or puts a jewel from hand to D (decreasing hand count, increasing D). There's no other constraints (like you can't hold more than some number). Essentially we can rearrange jewels between hand and D, with total moves limited to K.
Goal: maximize sum of hand after at most K moves. We can also stop early (use fewer than K operations).
We can think of sequence of operations. Equivalent to: we can choose a subsequence of jewels to eventually hold. But we can also discard jewels (by putting them back into D? But putting back into D doesn't remove them from hand? Actually putting back reduces hand, but it's still in D. The final hand consists of jewels currently in hand; jewels in D are not counted. So we want to end with a set of jewels in hand whose sum is max. We can take jewels from D and possibly put some back if they are negative to avoid reducing sum, or we can also take more than we want then put negative ones back, etc.
Because we have at most K operations, and each operation is either a take or a put. Let's denote the process: initially hand empty, D contains all N jewels in order. We can perform sequences like take some from left/right, then maybe later insert some back.
Observation: Operations are reversible? Not exactly but you can take a jewel and later put it back. The net effect can be thought of as we have a multiset of jewels that we have "selected" to be in hand at the end. But we might take extra jewels and then put them back, which costs extra operations. So it's optimal to never take a jewel that we will later put back, unless it helps to access other jewels? But since you can take from either end, you can take any subset of jewels in any order? The constraint is that D is a deque; you can only take from ends. However, you can also put back to ends. So you could take from left, then later put back to left, etc. This allows you to essentially "extract" any subset of jewels, but with additional moves to remove undesired jewels from the hand.
Think of it as: we have a sequence of jewels. We can perform a series of pops from left/right and pushes to left/right. This is reminiscent of the classic "AtCoder ABC 127 F? Actually there's a known problem: ABC 128 D? Or maybe it's similar to "AtCoder DP"? I recall a problem called "Deque" or "D - ???" from AtCoder. This is likely "AtCoder ABC 175 F"? Wait no, it's a typical problem: "Maximum Sum of Hand" with operations on deque. It's from AtCoder "ABC 125 D"? Not sure.
Let's derive solution.
We want to maximize sum of jewels in hand after at most K operations. Since we can discard negative jewels by not taking them or by putting them back, the optimal strategy likely involves taking some number of jewels from the left and right, then discarding some of the taken ones (by putting them back) that are negative.
But note: putting back also costs an operation. So if we take a negative jewel, we can later put it back to avoid decreasing sum, but that uses two operations (take + put). Alternatively, we could simply not take it in the first place, saving operations. So why would we ever take a negative jewel? Perhaps to access jewels that are deeper in the deque? Since you can only take from ends, if you want to get a jewel that is not at an end, you need to remove (take) the jewels in front of it from one side, and then you can take the desired jewel. Those removed jewels may be negative, but you can later put them back (maybe on the other side) to restore the deque? But the final hand sum only cares about what's in hand, not about D. So if we need to extract an interior jewel, we must take some jewels from ends to expose it. Those taken jewels are now in hand; we might want to put them back (or discard them) to avoid negative sum. However, putting them back might increase the sum if they are negative? Actually putting back removes them from hand, so if they are negative, removing them from hand increases sum (since they were negative in hand). So we want to get rid of negative jewels that we inadvertently took. But if we put them back, they go back to D and no longer affect hand sum. That costs an extra operation per negative jewel we discard.
Alternatively, we could keep them in hand if they are positive? But we would prefer not to keep negatives.
But maybe we can also rearrange order: after taking some jewels, we could put them back on the opposite side, thereby changing the order of D. This could allow us to access interior jewels more efficiently? But since we only care about final hand, maybe we can just take jewels directly from ends and never bother with interior ones unless we take intervening ones.
Wait: If we want to take a jewel that is not at either end, we must first remove all jewels from one side until that jewel becomes an end. Those removed jewels become in hand. Then we can take the desired jewel. After that, we could put back the removed jewels (maybe in same order or reversed) to restore D, but we don't care about D. However, we might also keep some of those removed jewels if they are positive. So essentially, we can pick any subset of jewels from the deque, but the total number of operations required to obtain that subset is not simply the size of the subset; it depends on how we extract them because we may need to temporarily remove other jewels.
But we are allowed up to K operations. So we need to find a sequence that yields a hand with maximum sum using <= K ops.
Observation: The operations A and B remove from D; C and D insert to D. Since we only care about final hand, the final state of D is irrelevant. So we can think of the process as: we start with D containing all jewels. We can perform a series of removals and insertions. Ultimately, the hand contains some jewels. The process can be seen as we have a multiset of jewels that are "taken" at some point and not returned. The net number of "takes" minus "puts" equals the size of hand. Also each take and each put counts as an operation.
Let x be number of take operations (A/B), and y be number of put operations (C/D). Then total ops = x + y ≤ K. At the end, hand size = x - y (since starts 0). All hand jewels come from some takes, and some may have been put back.
Instead of modeling sequence, we can think: We can choose to take some number of jewels from the left end and some number from the right end (in some order, possibly interleaved), and then optionally discard (put back) some of them. However, we might also take jewels that were originally not at ends but become ends after some puts? Because when we put back, we can put on either end, which could create new ends that contain jewels that were originally interior? But we can only put back jewels that we have in hand, which originally came from D. So we can put back a jewel to a different end, but that doesn't create a new jewel; it's just moving a jewel from hand to D. This could allow us to later take it again? That seems pointless because we could have just kept it in hand. Unless we want to reorder to take other jewels? For example, suppose we take leftmost, a negative jewel, then we put it to right end, then take it again? That would be wasteful. So probably optimal strategies never involve putting back a jewel that you later take again, because that would waste operations.
Thus, we can think of each jewel's journey: either it ends in hand (net taken and not returned) or it ends back in D (either never taken, or taken and later returned). The ones that end in D we don't care about. For those that end in hand, they must have been taken exactly once and never returned. For those that end back in D, either never taken (0 operations) or taken and returned (2 operations: take and put). Taking and returning a jewel might be beneficial if by taking it we can access another jewel that we want, and then we return it to avoid having it in hand (if it's negative). So the net cost for a jewel we want to keep is 1 operation (take). For a jewel we take temporarily (to access deeper ones) and then return, cost is 2 operations, and it contributes 0 to final sum (since not in hand). However, taking it temporarily also temporarily occupies hand, but that's fine; we can put it back later.
Therefore, the problem reduces to: We have a linear array of N jewels. We can perform a sequence of pops from left/right and pushes to left/right. This is akin to having a queue that we can modify. But perhaps we can characterize the reachable final hand sets with certain operation counts.
Consider a simpler model: Suppose we only take jewels from ends and never put back. Then the hand will contain some number of jewels taken from left and right. The total operations = number taken = hand size. The maximum sum would be the maximum sum of t jewels taken from the ends, where t ≤ K, and you must take a prefix from left and suffix from right (i.e., you take a certain number L from left and R from right, with L+R = t, and you cannot take interior without taking all outer ones). In that case, you simply choose L and R such that L+R ≤ K, and sum of first L and last R values, possibly after ordering? Actually the order of takes doesn't matter; you can take left and right in any interleaving, but the set of jewels you can obtain by only taking (without puts) is exactly any union of a prefix and a suffix of the original array, with the prefix and suffix possibly overlapping? But if you take more than N, you would exhaust all jewels. Since total taken ≤ N, it's just a prefix and suffix that are disjoint (if L+R ≤ N, they are disjoint unless they overlap which would require taking more than N). So the set is {V1..VL} ∪ {V_{N-R+1}..V_N}. This is typical. Then sum is sum of those.
But we can also do better by discarding negative jewels among those taken: if we take some prefix/suffix that includes negatives, we could discard them by putting them back, costing extra ops. So net we might take more jewels (including negatives) to get to deeper positive ones, then put back the negatives. This might increase sum beyond just taking directly.
For example, consider array: [-5, 100]. N=2, K=1. If we only take, we can take leftmost (-5) or rightmost (100) with one operation. Max sum=100. With K=2, we could take leftmost (-5) and then take rightmost (100) but that's 2 ops, sum=95, not as good as just 100. But maybe we could take leftmost (-5), put it back? That would be two ops, hand empty, not beneficial. Or take leftmost (-5), put it back on left (still -5 in D), then take rightmost? That would be three ops. So no benefit.
Consider another: [-5, 1, 100], K=2. Directly take 2 jewels: you could take rightmost (100) and leftmost (-5) sum=95; or take rightmost (100) and middle? Can't take middle without taking one end first. With 2 ops, you could take leftmost (-5) and then rightmost (100) sum=95; or take leftmost (-5) and then put it back? Not helpful. But perhaps take leftmost (-5) (op1), then take new leftmost (now 1) (op2) sum=-4, worse. So best is 100 with 1 op. But maybe we can do: take leftmost (-5) (op1), put it back on right (op2) — hand empty; then take leftmost (1) (op3) but K=2 only. So not.
Consider example where interior positives are behind negatives. Suppose array: [-10, 5, 6], K=2. With only takes: we can take 2 jewels: options: leftmost -10 and next left? Actually we can take leftmost -10 (op1), then leftmost becomes 5, take it (op2) sum=-5; or take rightmost 6 (op1) and leftmost -10 (op2) sum=-4; or take rightmost 6 and next right? Actually can take rightmost 6 (op1) then new rightmost 5 (op2) sum=11. But can we achieve 11? Taking rightmost 6, then rightmost becomes 5, take it: sum=11. That's taking the two rightmost: values 5 and 6? Wait order: original: [-10,5,6]. Rightmost is 6. After taking 6, D becomes [-10,5]. Then rightmost is 5. So take 5: sum=11. So we can get sum=11 with two ops, which is better than 6 with one op. So max sum=11. However, note that we could also take leftmost -10 and rightmost 6: sum=-4. So best is 11.
But is there a way to get both 5 and 6 without -10? Yes by taking from right side, we didn't need to take -10. So no need to discard.
Now consider array: [-5, -2, 100], K=2. Direct takes: we can take rightmost 100 and leftmost -5 sum=95; or take rightmost 100 and next rightmost -2? Actually after taking 100, D becomes [-5,-2]; rightmost is -2, taking gives sum=98; or take leftmost -5 then rightmost 100 sum=95; or take leftmost -5 then next leftmost -2 sum=-7. So best is 98 (100 + (-2) = 98). But maybe we could take leftmost -5 (op1), put it back on right (op2) -> D becomes [-2, -5? Actually original D: [-5,-2,100]. After op1 take leftmost -5: D=[-2,100], hand={-5}. Op2: put -5 to right: D=[-2,100,-5], hand empty. Then op3 could take leftmost -2? Not allowed K=2. So not. Could we take leftmost -5 and then take rightmost 100? That's 2 ops sum=95, worse than 98. So 98 is best.
But 98 includes a negative -2. Could we avoid that? With K=2, to get only 100, we need 1 op. So sum=100 is better than 98? 100 > 98. Actually 100 > 98, so best is take only 100 (1 op). So max=100. But if K=2, still 100 is best because you can stop after 1 operation. So we can always use fewer operations. So we should consider up to K; we can stop early. So best sum might be with fewer ops.
Now consider scenario where the best sum involves taking many positives but also some negatives, but discarding negatives by putting them back. For that, we need to take extra operations to put back negatives. But if those negatives are blocking access to more positives, it might be worth it.
Example: N=4, values: [-5, 10, 10, -5]. Suppose K=3. With only takes: possible sets: take up to 3 from ends. Options: take two 10s? To get both 10s, you need to take either from left or right. The leftmost is -5, rightmost is -5. To get the first 10 from left, you must take -5 first (since it's leftmost). So to get both 10s, you could take leftmost -5 (op1), then leftmost becomes 10, take it (op2), then to get the other 10, you could take rightmost -5? Actually after two ops, D: [10, -5] (since after taking -5 and left 10, we have the original array: [-5,10,10,-5]. Taking leftmost -5 gives D=[10,10,-5]. Then taking leftmost 10 gives D=[10,-5]. Now the remaining 10 is at left? Actually D=[10,-5], leftmost is 10, rightmost -5. To get the other 10, we could take leftmost 10 (op3) -> sum = -5 + 10 + 10 = 15. But we used 3 ops, sum=15. Alternatively, we could take rightmost -5 (op1), then rightmost 10 (op2), then leftmost 10 (op3) -> sum = -5+10+10=15 as well. Could we achieve 20? To get both 10s and avoid negatives, we would need to discard the -5s. For that we would need to take them and then put them back, but that would cost extra ops. With K=3, we can't afford to discard. But what about K=4? With 4 ops: one scheme: take leftmost -5 (op1), take rightmost -5 (op2), now hand contains -5 and -5 (sum -10), D=[10,10]. Then take leftmost 10 (op3), take rightmost 10 (op4) -> hand sum = -10+20=10. That's worse. Or take left -5 (op1), put it back on right (op2), now D becomes [10,10,-5]? Actually after op1, D=[10,10,-5], hand={-5}. op2: put -5 to right: D=[10,10,-5,-5], hand empty. Then take left 10 (op3), take right 10 (op4): sum=20. That uses 4 ops, sum=20. So with K=4, we can achieve 20 by taking and discarding the negatives. With only takes (no puts) we could take left -5, left 10, left 10 (but after taking -5 and 10, the leftmost becomes 10? Wait after taking -5 and 10, D=[10,-5]? Actually original [-5,10,10,-5]. Take left -5 (op1): D=[10,10,-5]. Take left 10 (op2): D=[10,-5]. Take left 10 (op3): D=[-5]. Sum = -5+10+10=15. That's 3 ops. To get 20 with only takes, you would need to take all four, sum=10. Not good. So putting back negatives enables 20.
Thus, discarding negatives (by putting them back) can improve final sum because you can "access" interior positives without keeping the negatives that you had to remove to get to them. In the above, to get both 10s, you must remove the -5s that block them? Actually both 10s are not blocked by negatives on both ends? The array is symmetric: -5 at left, 10,10, -5 at right. To get the left 10, you must remove left -5 first (since it's at the left end). Similarly to get the right 10, you must remove right -5 first. But if you want both 10s, you could remove left -5 and right -5, then take both 10s. That would be 4 takes: sum = -5-5+10+10=10. But you can do better by removing the -5s and then putting them back before taking the 10s? That would be: take left -5, take right -5 (2 ops), hand has -5,-5 sum -10. Then put left -5 back? But we want to free the 10s. After taking both -5s, D becomes [10,10]. The 10s are now at both ends. So we can take them directly. If we take them without putting the -5s back, hand sum becomes 10. But if we put the -5s back before taking the 10s, that would be: after taking both -5s, hand has -5,-5; we could put one -5 back (op3) to D, say to left, making D=[-5,10,10], hand has -5; then take left 10? Actually leftmost becomes -5, we would need to take it again to get to 10, which is worse. So that's not beneficial. The trick is: take left -5 (op1), put it back on right (op2), then take left 10 (op3), take right 10 (op4)? Let's simulate:
Initial: D=[-5,10,10,-5]
op1 A: take leftmost -5 -> D=[10,10,-5], hand={-5}
op2 D: put -5 to right (choose jewel -5 from hand, insert to right) -> D=[10,10,-5,-5], hand={}
op3 A: take leftmost 10 -> D=[10,-5,-5], hand={10}
op4 B: take rightmost -5? Actually rightmost is -5, but we want 10. After op3, D=[10,-5,-5], rightmost is -5, leftmost is 10. To get the other 10, we could take leftmost again? But leftmost is 10? Wait D=[10,-5,-5], leftmost is 10, rightmost -5. So we can take leftmost 10 (again) but that would be the same as the one we already have? Actually there is only one 10 left? Let's track: originally there are two 10s. After op1 and op2, both 10s are still in D. After op3, we took one 10, D now has [10, -5, -5]? Wait after op2, D=[10,10,-5,-5]. So after op3 (take leftmost), we remove leftmost 10, D becomes [10,-5,-5]. That leaves one 10 and two -5. To get the remaining 10, we could take leftmost again? Leftmost is 10, yes! So op4 take leftmost 10 -> D=[-5,-5], hand={10,10}. So after 4 ops, hand sum=20. So indeed we used: take -5, put -5 back (on right), then take 10, take 10. That yields sum 20. This required 4 ops. The key is that we put the -5 back on the opposite side, so that after putting it back, the -5 is now at the right end, not blocking the left side. Then we can take the two 10s from the left side without having to take the other -5? But we still have a -5 on the right but we didn't need to take it. However, note that after op2, D=[10,10,-5,-5]. So the leftmost two are 10 and 10? Actually order: original: [-5,10,10,-5]. After taking left -5, D=[10,10,-5]. Then putting -5 to right: we append -5 to right, so D becomes [10,10,-5,-5]. The order is now: leftmost: 10, then 10, then -5, then -5. So the two 10s are at positions 1 and 2 from left. So taking leftmost twice gives both 10s. The -5s remain on the right. So we never need to take them. So we effectively "discarded" the left -5 by moving it to the right, out of the way, so we can access the 10s directly. This cost 2 ops for that -5 (take and put). Then we took the two 10s (2 ops) for total 4 ops. The other -5 was never touched. So final hand has both 10s, sum=20. So discarding a negative jewel by taking it and putting it on the opposite end can be beneficial.
Thus, the operations allow us to "reorder" the deque to some extent, by taking elements from one end and putting them back on the other end, effectively rotating elements. But we only care about final hand sum; we can rearrange the deque to bring desirable jewels to the ends and push away undesirable ones, using extra operations.
In general, we can think of the process as: we are allowed up to K operations, each operation either removes an element from an end (and adds to hand) or inserts an element from hand to an end. This is like we have a multiset of elements that we can temporarily hold and then possibly reinsert. Equivalent to: we can perform a sequence of operations that results in some set of elements being kept in hand, with a total number of operations equal to (number of kept elements) + 2 * (number of discarded elements that were taken and then put back). However, the number of discarded elements may be constrained by the need to access interior elements. But maybe we can think in terms of "we choose a subsequence of the original array to keep, and we may also choose some elements to remove temporarily to access others, but those removed temporarily are later put back."
But there might be a more systematic approach. Since N is small (≤50) and K ≤ 100, we can perhaps consider all possibilities of how many elements we take from left and right (including ones we later put back). Because the process can be interpreted as: we will perform some number of take operations (A/B) and some number of put operations. Let a be total takes, b be total puts, a+b ≤ K, final hand size = a-b. The jewels we end up keeping are some subset of those taken. The ones taken and then put back are the ones we discarded. The takes are from ends at various times, and puts are to ends.
Given small N, we could try to simulate all possible sequences? That would be huge (4^K). Not feasible.
Alternate viewpoint: This is a classic AtCoder problem: "D - ..?" I recall a problem "ABC 128 D - equeue"? Actually there is "ABC 126 D"? Let's search memory: There is a problem called "equeue" from AtCoder Beginner Contest 128 D? Wait ABC 128 had "D - equeue"? I think there is a problem "D - equeue" from ABC 125? I'm not sure. I recall a problem about a deque with operations A, B, C, D and maximizing sum, with constraints N≤50, K≤100. Yes, that is AtCoder Beginner Contest 128 D: "equeue" maybe? Actually AtCoder has a problem "D - equeue" from ABC 125? Let's check: I recall a problem with exactly these operations A, B, C, D. It might be from AtCoder Beginner Contest 127 D? No, 127 D is "Integer Cards". 126 D is "Even Relation". 125 D is "Flipping Signs". 124 D is "Handstand". So maybe it's from ABC 128? Actually I think it's from ABC 128 D: "equeue". I've seen a problem "equeue" in ABC 125? I'll search memory: The problem statement with operations A, B, C, D and dequeue appears in AtCoder Beginner Contest 128 D: "equeue" indeed. I've solved it before. The typical solution: iterate over how many gems we take in total (say t), and how many we put back (discard). Actually the solution: for each possible number of elements taken from left (L) and right (R) such that L+R ≤ K, we consider the multiset of taken elements. Among those, we can discard up to some number of negative ones (since we can put them back) but we are limited by the number of operations left after taking: we have K - (L+R) operations remaining, which can be used to put back negative jewels (each put back uses one operation). However, we can also put back at most (L+R) jewels (since we can only put back what we have taken). Also we may put back any jewels, not necessarily negative? But we wouldn't put back positive ones. So the optimal is to discard as many negative taken jewels as possible, subject to the limit of puts (which cost 1 each). But also note that we might be able to reorder by taking from one side and putting to the other, which could allow us to take interior positives without taking all negatives on that side? However, the classic solution for "equeue" uses the idea that we consider taking x jewels from left and y from right, collecting them into a multiset, then sorting and discarding up to d negative numbers, where d = min(number of negatives in the multiset, remaining operations). But is that always optimal? Let's recall: In AtCoder ABC 128 D "equeue", the problem is exactly this: There is a dequeue with N gems, values V_i, K operations. Operations A,B,C,D as described. Find max sum. The solution is: For each total number of taken gems (from ends) T = 0..min(N,K), and for each split L from 0..T, R = T-L (L from left, R from right). But careful: L+R ≤ N obviously. Then we have taken L from left (the first L) and R from right (the last R). But does this capture sequences where we take from left, then later put some back, and then take more from left/right? For example, in the earlier example to get both 10s with K=4, we took L=0 from left? Actually we took from left: we took leftmost -5 (that's one from left), then we put it back to right (so it's not kept), then we took two 10s from left. So total taken elements (including those later put back) from left: we took -5 and two 10s? Actually we took -5 (from left), then later we took 10 (from left), then another 10 (from left). That's three takes from left, and zero from right. But we also performed a put (of -5 to right). So total ops = 4. According to the "take L from left, R from right" approach, L would be number of takes from left that we eventually keep? But we also took -5 and put it back, so it's not kept. The classic solution typically considers that we first take some elements from left and right (possibly more than we keep) and then put back some of them (the negative ones). However, the set of taken elements is exactly a prefix of left and suffix of right, because we can only take from ends initially. But after we put back some, we can then take additional elements from the new ends, which may not be from the original prefix/suffix? In the example, after putting -5 back to right, the deque becomes [10,10,-5,-5]. Then we take two 10s from left. Those 10s were originally at positions 2 and 3. They are not part of the original prefix or suffix if we define prefix as first L and suffix as last R? Actually the original array indices: 1:-5, 2:10, 3:10, 4:-5. The two 10s are at indices 2 and 3. In the classic approach, if we set L=2 (take first two from left), we would take -5 and 10. That's set = {-5,10}. If we set R=2 (take last two from right), we take -5 and 10. That's set = {10,-5}. But taking L=2 and R=0 gives set = {-5,10}. Taking L=0,R=2 gives {10,-5}. Taking L=3,R=0 would take first three: -5,10,10. That's set = {-5,10,10}. Taking L=3,R=1? Not allowed because L+R ≤ N. But our solution involved taking L=3 from left? Actually we took -5, then later took 10 and 10, total three takes from left. So L=3, R=0. That set is {-5,10,10}. Then we have one put operation (we put back -5). So we keep {10,10}. The classic approach: for each L,R with L+R ≤ K, we consider the multiset of taken elements = first L + last R. Then we can discard up to d negative numbers, where d ≤ K - (L+R) (since each discard is a put operation). The max sum would be sum of taken elements minus the sum of the smallest (most negative) ones we discard, limited by d. So for L=3,R=0, taken = [-5,10,10], sum=15. We have K - (L+R) = 4-3 = 1 discard available. We can discard the -5 (most negative), resulting sum = 20. That matches our optimal! So the classic approach yields the correct answer.
Now consider L=2,R=0: taken=[-5,10], sum=5, discard limit = 4-2=2, but only one negative, discard -5 -> sum=10. L=0,R=2: taken=[10,-5], sum=5, discard -5 -> sum=10. L=1,R=1: taken=[-5,-5]? Wait first 1 from left = -5, last 1 from right = -5, sum=-10, discard limit=2, discard both -> sum=0. L=2,R=1: L+R=3, taken = first2 [-5,10] + last1 [-5] = [-5,10,-5], sum=0, discard limit=1, discard -5 -> sum=5? Actually discard one -5 yields sum=5? After discarding one -5, we have [-5,10] sum=5, or [10,-5] sum=5. That's 5, not 20. So L=3,R=0 gave best.
Thus, the classic solution seems to work. Does it always capture all possible strategies? I think yes, based on reasoning that any sequence can be transformed into one where all takes happen before all puts, and the set of taken jewels (including those later discarded) is a union of a prefix and a suffix of the original deque. Because you can only take from ends, and any put operation puts a jewel back to an end, potentially making it available for later takes. But the classic solution's assumption is that the optimal strategy can be represented as: first, perform some number of A and B operations (taking jewels from ends), then perform some number of C and D operations (putting jewels back). And during the taking phase, we only take from the original ends? But after we put back, we might take from the new ends, which could be jewels that were originally interior. However, note that if we interleave puts and takes, we could effectively take interior jewels. But the claim is that any such interleaving can be simulated by a strategy where we first take a set of jewels that is a union of a prefix and suffix (the ones we ever take, including those we later put back), and then we put back some of them (the negatives). Because if we put back a jewel and later take it again, that would be wasteful; so optimal sequences likely don't involve taking the same jewel twice. Also, we never need to put back a jewel and later take a different jewel that was originally not at ends? But we already saw putting back a jewel to the other end allowed us to take an interior jewel without having taken it earlier. In that example, we took -5 (a prefix element), put it to right, then took two 10s (which were originally interior). The set of jewels we ever took (including the discarded -5) is: -5, 10, 10. That's first 1 (prefix) and also two interior? But the 10s are not from the suffix; they are from indices 2 and 3, which are not a suffix. However, note that the set of taken jewels is {index1, index2, index3}. That's a prefix of length 3? Indeed indices 1,2,3 are the first 3 elements. So they form a prefix! Because we took -5 (index1), then after putting it back, we took two 10s from left, which were originally indices 2 and 3. So the total taken set (including the discarded) is the first three elements (a prefix). So indeed, the taken set is a prefix (or suffix, or combination of prefix and suffix) but in this case it's a prefix. Could it be a combination of prefix and suffix? Suppose we take some from left, then put some back, then take from right, etc. The set of indices ever taken might be some left segment and some right segment, but possibly with overlap? But the key is that any element we take must become an end at the moment we take it. Initially, only ends are indices 1 and N. After we take some from left, the left end moves right. After we take some from right, the right end moves left. If we put back an element to an end, that element becomes the new end, potentially extending the deque beyond the original boundaries? Actually the original deque has fixed elements; putting back an element that was taken earlier does not create new elements beyond the original N; it just places that element at an end. So the set of elements remaining in D is always a subsequence of the original array? Initially, D is the whole array. When we take from left or right, we remove elements. When we put back, we insert the element at an end. So the deque D can contain elements that are not in their original order? Actually when we take an element and put it back on the same side or opposite side, we change the order. For instance, we took -5 from left and put it to right, resulting in D = [10,10,-5,-5] which is not a contiguous subarray of the original because the order changed: the -5 moved from left to right. So the remaining D is not necessarily a contiguous subarray; it can be a permutation of a subset? But the set of elements in D is a subset of original (since we never create new elements). However, after operations, the order can change. This could allow us to take interior elements without having taken all elements on that side originally? But in the example, after moving -5 to right, the two 10s become the leftmost elements. So we could take them. Those 10s were originally at indices 2 and 3, which were not ends initially. But after we removed the left -5 and put it on the right, the remaining elements (10,10,-5) are in original relative order? Actually original: [-5,10,10,-5]. After removing left -5, we have [10,10,-5]. After putting -5 to right, we get [10,10,-5,-5]. So the 10s are now at positions 1 and 2. So we took them. The set of indices we ever took is {1,2,3}. This is a contiguous prefix (indices 1,2,3). So it seems that any element we take must be from either the original left side segment or original right side segment? But index 3 is not originally leftmost or rightmost? It is interior, but after removing index1 and index4 maybe it becomes an end. In general, if we take some elements from left and right, the remaining D is a contiguous subarray (since we only remove from ends). But when we put back, we can insert at ends, which can break contiguity. For instance, after we take leftmost -5, D is [10,10,-5] (contiguous subarray indices 2,3,4). Then we put -5 back to right, D becomes [10,10,-5,-5]. This is not a contiguous subarray of original because we have -5 (index1) appended to the right of index4. But the set of elements is {index2, index3, index4, index1}. It's a permutation of the whole set. But after that, the leftmost elements are index2 and index3. So taking them corresponds to taking elements from the original contiguous block? They are indices 2 and 3, which are contiguous and lie between the removed left element and the right element? Actually they were originally adjacent. So maybe the set of indices we ever take (including discards) always forms a contiguous block? Not necessarily; consider taking from left, then putting back to left, then taking from right, etc. Could we ever take an index that is not from a prefix or suffix of the original array? Suppose we take leftmost a, then put it back to left, then take rightmost b. The set taken is {a,b}. That's a from left, b from right. That's prefix + suffix. If we take a from left, put it to right, then take b from right (which might be a different element), we take {a,b} again. So it's still a from left and b from right. If we take a from left, then take b from left (after some puts), b might be originally from right? No, if we only take from left, we take elements in order from left. After putting back a to right, the leftmost becomes the next original element. So any take from left after any sequence of puts will always take an element that was originally somewhere in the left part of the array (i.e., with index increasing as we take more from left). Similarly, takes from right will take elements originally from the right part. But could we take an element that is originally from the left after we have taken some from right and put them back to left? Possibly. For example, take rightmost element (original index N) and put it to left; then take leftmost. The leftmost would be that element we just put, which is originally from the right. So we are taking an element originally from the right via a left take after putting it to left. So the set of indices we take could be any subset? Let's examine: We start with original array. We can take elements from ends, and put them back on ends. This allows us to reorder the deque. Could we eventually take an interior element without having taken all elements on one side? Suppose we want to take the element at index i (not at ends). We could take elements from left up to i-1 and put them all to the right (or discard), then take element i from left. That would involve taking all left-side elements before i. Those left-side elements might be negative; we could then put them back (maybe to right) after we have taken i. But we would have taken them. So the set of indices taken includes all those left-side elements. Similarly, if we approach from right, we would take all elements from right side after i. So any element we take ultimately must be accompanied by taking all elements that were originally on one side of it, unless we put them back before taking it? But we can put them back after taking it, but we still had to take them at some point. So the total taken set (including discards) will be a set of indices that consists of some prefix (indices 1..L) and some suffix (indices N-R+1..N), possibly with overlap if L+R > N (but that's just whole array). Additionally, we might also take some elements from the middle after putting some from the other side? Actually if we take from left some elements, put them to right, then take from right some elements, we could take elements that were originally from the left after they've been moved? That would mean we take an element twice? Not allowed because once taken, it's in hand; we cannot take it again unless we put it back first. But we could put it back and then take it again; but that would be wasteful. In any optimal solution, we would not take the same jewel more than once, because that would cost extra operations without gaining new jewels (since net effect on hand is zero if we take and put back). However, we might put back a jewel and later take a different jewel that was originally adjacent? But that doesn't cause taking same jewel twice. So the set of jewels we ever take (including those we later put back) could be any subset? Let's test: can we take an interior element without taking all elements on one side? Suppose N=5, values: a b c d e. Want to take c without taking a or b or d or e. Is that possible? Initially ends are a and e. To get to c, we need to remove a and b from left, or d and e from right. Removing means taking them into hand. So we must take a and b (or d and e). After taking them, they are in hand. Then we can take c. At this point we have a,b,c in hand. We could then put back a and b (maybe to the other side) to discard them. So the taken set includes a,b,c. That's prefix of length 3 (a,b,c). If we instead remove from right: take e,d then c, taken set is c,d,e (suffix of length 3). So indeed, to take an interior element, we must take all elements on one side of it. Therefore, the set of indices we ever take (including those we discard) must be a contiguous block from either the left or the right? Actually it could be a union of a prefix and a suffix if we take from both sides? For example, we could take a from left, then e from right, then put a to right, then take b from left? Let's try: start [a,b,c,d,e]. Want to take b and d without taking c? Could we? To take b from left, we must take a first? Because b is not at an end until a is removed. So we must take a. So taken set includes a and b. Similarly, to take d from right, we must take e first? d is not at right end until e is removed. So we must take e. So taken set includes a,b,d,e? But what about c? Not necessarily. After taking a and b from left, the deque becomes [c,d,e] (if we haven't put back). Then we can take e from right (now e is at right), then d from right? But if we take e, then deque is [c,d], then we can take d from right. So taken set includes a,b,e,d. That's prefix (a,b) and suffix (d,e). This is a union of a prefix and a suffix. There is a gap (c) not taken. So indeed, the total taken set can be described as: we take some number L from the left (the first L elements) and some number R from the right (the last R elements). Because any element taken from the left must be among the first L elements for some L, and any taken from the right must be among the last R elements. Moreover, if we take an element that originally was from the left after it was moved to the right (by putting it back), that would mean we took it from the right after it was put there. But then it was originally from the left, so it would be counted in the left-side taken set? Actually if we take a left element, it's in the prefix. If we later put it back to the right and then take it again from the right, that would be taking the same element twice, which is wasteful. So in an optimal solution, we wouldn't do that. So we can assume each element is taken at most once. Thus, the set of elements ever taken is a subset of the union of a prefix and a suffix. And if we take an element that is not in the prefix or suffix, it must be interior, which requires taking all elements on one side, making it part of a prefix or suffix block.
What about taking an element from the middle after putting some elements from the other side to the other end? For example, start [a,b,c,d,e]. Suppose we take a from left, put it to right -> D=[b,c,d,e,a]. Then take b from left -> D=[c,d,e,a]. Then we have taken a and b. Then we could put b to right -> D=[c,d,e,a,b]. Then take c from left -> D=[d,e,a,b]. So taken set includes a,b,c. That's prefix of length 3. So still prefix.
What if we take e from right first, put it to left, then take d from right? That would be suffix.
So it seems any optimal sequence can be transformed into one where we first perform a series of takes (from left and right) without any puts in between? Not exactly, because we saw the optimal needed a put in between to move the -5 to the right, enabling taking both 10s without taking the other -5. However, in terms of the set of taken elements (including discards), that set is a prefix of length 3. And the put operation was used to discard one of them. In the "take first L elements, then discard some" representation, we first take the first L elements (by repeatedly taking from left). That would put them all in hand. Then we can put back some of them (the negatives). But is that equivalent? If we take the first 3 elements (-5,10,10) in order, we have them in hand. Then we have K - 3 = 1 operation left, which we can use to put back the -5 (the most negative). That yields hand {10,10} sum=20. That's exactly the same as our earlier strategy with interleaving. So the strategy "take L elements from left (by repeatedly doing A), then optionally put back some of them" works and yields the same outcome. But is it always possible to take a prefix of length L without any puts? Yes, simply do A L times. That will take the first L elements in order. Similarly, taking a suffix from the right: do B R times. But what about taking a mixture of prefix and suffix? If we take L from left and R from right, we might take them in any order, but the set of taken elements will be the first L and last R. However, if L+R > N, we would be taking some elements twice? Actually we cannot take more than N distinct elements. So we require L+R ≤ N. So the set of taken elements is the union of first L and last R, which may overlap if L+R > N? But if L+R > N, the prefix and suffix overlap, meaning we would be taking some elements twice? But we cannot take an element twice without putting it back in between. However, if L+R > N, then the union would be the whole array, but we might be counting some elements twice. To avoid double-counting, we should consider L+R ≤ N. Usually the solution enumerates L from 0 to min(N,K), and R from 0 to min(N-L, K-L). So L+R ≤ N.
Now, after taking L from left and R from right (total T = L+R takes), we have T elements in hand. We have used T operations. Then we have remaining operations up to K - T, which we can use to put back some of these taken elements. Since putting back a negative increases sum (removing negative from hand), we would put back the most negative ones among the taken set, as many as allowed (up to K - T). However, we could also put back positive ones? That would decrease sum, so not optimal. So we put back the most negative (lowest values) up to d = min(K - T, T) times. But careful: We can put back at most the number of elements we have (T). Also each put back uses one operation. So we can discard up to d elements. The sum after discarding d most negative is sum of taken elements minus sum of the d smallest (most negative) values among them. But we could also choose to discard fewer than d if discarding a positive would reduce sum, so we only discard negatives. So we can discard up to d, but we would discard only the negatives, and we can discard at most the number of negatives in the taken set.
Thus, for each (L,R) with L+R ≤ min(N,K) (since we cannot take more than N distinct elements; also we may take fewer than K because we might not use all operations, but we can also take less and then discard some), we compute the sum of taken elements (first L and last R), sort the taken list, and then consider discarding up to d = min(K - (L+R), number of negatives in taken) smallest elements (most negative). Actually we can discard any subset of taken elements, but optimal is to discard the most negative ones, as discarding a positive reduces sum. So we should discard as many of the most negative as we can, but only if they are negative. So we should compute the sum after discarding the x most negative values, for x from 0 to min(d, count_negatives). But we can also choose to discard fewer than d; we want maximum sum, so we can compute: let taken array A of length T. Sort A. Let prefix sums of sorted array (from smallest to largest). The sum after discarding the first x (most negative) is total_sum - sum_{i=0}^{x-1} A[i] (where A sorted ascending). For each x such that x ≤ d and also x ≤ T, compute candidate sum. Actually we only consider discarding negatives, so we can only discard while A[x-1] < 0. So we can iterate x from 0 up to min(d, T) and break when A[x] >= 0 (if sorted ascending). Or we can just compute: let negative values sorted; we can discard up to d of them; so sum_after = total_sum - sum_of_discarded, where discarded are the smallest (most negative) min(d, #neg) values. But is it ever beneficial to discard a positive to later be able to discard a more negative? No, discarding a positive reduces sum, so not beneficial. So we only discard negatives.
Thus, for each (L,R), candidate max = total_sum - sum_of_smallest_x where x = min(d, number_of_negatives_with_negative_value). However, note that we could also discard zero and stop early, so we take max over x=0..min(d, T) but only beneficial if A[x-1] < 0. Actually we can compute directly: let sorted_taken = sorted(taken). Let prefix_sum_sorted[i] = sum of first i elements (0-indexed). Then for x from 0 to min(d, T): candidate = total_sum - prefix_sum_sorted[x] (if prefix_sum_sorted[x] is sum of x smallest). Take max over x where we may also consider not discarding all if some of the smallest are positive? But if smallest are positive, then discarding any reduces sum, so best is x=0. So we can just compute for x up to min(d, T) and take max. The max will naturally be at x where we stop before positives.
Thus, the answer is max over L,R such that L+R <= min(N,K) of ( max_{0 <= x <= min(K - (L+R), L+R)} (total_sum - sum_of_smallest_x) ). We can also consider taking fewer than L+R? Actually we are forced to take exactly L+R elements to have that set. But we could also choose to take fewer than K operations overall. Our enumeration includes all L,R with L+R <= K (since T = L+R <= K). But also we might not use all K operations; that's fine because we can stop early. Our candidate includes the case where we don't use all ops (i.e., x can be less than d, but we could also have T < K and not use remaining ops). That's captured because we are not required to use all operations; the max over x up to d includes x possibly 0 even if d>0. So it's fine.
Edge: We might also consider sequences where we take more than N elements? Not possible because there are only N distinct jewels; we could take, put back, then take again, but that would involve taking the same jewel multiple times. Could that be beneficial? For example, take a positive jewel, put it back, then take it again? That would cost 2 ops and net effect zero (hand unchanged). Not beneficial. Taking a negative, putting it back, then taking it again? That would be even worse. So we can ignore taking same jewel twice.
Thus, the classic solution seems correct: iterate L from 0 to min(N,K), R from 0 to min(N-L, K-L). For each pair, we construct a list of taken values: first L elements (V[0..L-1]) and last R elements (V[N-R..N-1]). We compute total sum. We sort the list. Then we can discard up to d = K - (L+R) elements (puts). For each possible discard count x from 0 to min(d, len(list)), we compute candidate = total_sum - sum_of_smallest_x (where smallest_x is the sum of the x smallest values). Keep max.
Complexity: N <= 50, K <= 100, so L,R up to 50, enumerating all pairs O(N^2) ~ 2500, sorting list up to length 50, discard up to 50, so trivial.
But is this always optimal? I recall that this is indeed the solution for AtCoder ABC 128 D / ABC 125 D? I'll double-check with more tricky cases.
Consider scenario where we might want to take some elements from left, then put back some, then take more from left beyond the original L? But that would correspond to a larger L. Because if we later take more from left after putting some back, those additional takes are from the original array beyond the initial L? Let's examine: Suppose we take first L1 from left (by A operations), then we put back some of them (maybe not all), then we take more from left. After putting back, the left end might now contain some of the previously taken elements that we put back. If we put them back to the left, they become the new leftmost. Then taking from left again would take those same elements again (which we already had). That would be retaking the same element, which is wasteful as argued. If we put them back to the right, they become rightmost, so they don't affect the left end. So after taking L1 from left and putting some back to right, the left end becomes the (L1+1)-th original element (since