We need to read multiple test cases, each with n, x and list of n integers. We need to compute maximum sum <= x achievable by using any number of each element (unbounded knapsack). That's classic unbounded knapsack (coin change) where we want max value not exceeding capacity. Constraints: n, x up to 3000, T up to 10. So total operations T * n * x = up to 10 * 3000 * 3000 = 90 million, maybe borderline but in Python could be okay with efficient loops? 90M might be a bit high, but we can optimize using DP with array of size x+1, and for each coin iterate over capacities? Standard unbounded knapsack: dp[j] = max achievable sum for capacity j. For each coin value a, we can do for j from a to x: dp[j] = max(dp[j], dp[j-a] + a). Since we want sum exactly the item weight equals its value (since sum of values is what we care about). Actually it's like we have items with weight = value = a. So dp[j] = max sum achievable not exceeding j. The DP will fill dp[0..x] where dp[j] <= j. Since weights=values, the recurrence dp[j] = max(dp[j], dp[j-a] + a) works. This is typical coin change max amount.
Complexity O(n * x). 3000*3000=9e6 per test case, times up to 10 = 90e6, which is okay if implemented well in Python? Possibly within time if optimized (using list and loops, but 9 million integer operations per test case is fine; 90 million might be a bit heavy but probably still passes given typical time limits (1-2 secs?). But we can also use a more efficient method: Since we just need max sum <= x, and items can be used unlimited, this is essentially the classic "coin change" to achieve the closest to x. Another approach: Compute the minimum value among coins, but not needed.
But note: The DP described yields the exact maximum achievable sum for each j. However, since we can use unlimited multiples, we could also use a greedy if coins have some property? But not general; DP is safe.
Alternatively, we can do a DP using boolean reachable sums? But we need max sum, so DP with integer works.
Since x <= 3000, we can also use a bitset approach: maintain a bitset of reachable sums, then shift OR with itself? But with unlimited copies, we need to compute reachable sums using unbounded knapsack: we can use a BFS from 0, adding each coin repeatedly; it's essentially computing all sums <= x that can be formed. Then take max. That's similar to DP.
Simplify: dp = [False](x+1); dp[0]=True; for each coin a: for i in range(a, x+1): if dp[i-a]: dp[i]=True. That's unbounded? Actually careful: The loop order for unbounded knapsack (infinite coins) is to iterate i from a to x, allowing multiple uses: because when we process each coin, we consider using it after possibly having used it earlier in the same pass. That's correct for infinite supply when we iterate i ascending. So we can compute reachable sums boolean. Then answer = max i such that dp[i] is True. That's simpler and might be faster because it's boolean operations. But both are O(nx). Boolean operations might be slightly faster.
But note: In the coin change problem for max sum, we might also get answer directly. So either works.
Given constraints are small, any approach is fine.
Edge case: no selection sum 0 always possible.
Now, let's implement:
def max_sum_unbounded_knapsack(x, coins):
dp = [False]*(x+1)
dp[0] = True
for a in coins:
for i in range(a, x+1):
if dp[i-a]:
dp[i] = True
# find max i where dp[i] True
for i in range(x, -1, -1):
if dp[i]:
return i
return 0
But wait: This DP yields all sums that can be formed exactly. But the question asks for maximum sum that is as close as possible but not exceeding x. If we can form sums exactly up to x, answer is the highest reachable exact sum <= x. That is fine. However, is it possible that we cannot form any exact sum except 0, but we might get a sum less than x but not exactly some value? Wait, sum is formed by selected numbers, so it is exact sum of some combination. So answer is the maximum exact sum <= x. So boolean reachable sums works.
But what if we can form sums beyond x by using some combination? No, we only consider combinations whose sum <= x. So DP ensures we don't exceed capacity. So it's correct.
However, there is nuance: In unbounded knapsack, we usually compute dp[j] as maximum achievable sum for capacity j; dp[j] may be less than j even if we cannot fill exactly. But dp[j] will be the max sum that can be achieved with total weight <= j. In the boolean approach, we only track exact sums, but we might be able to achieve a sum less than j that is not an exact sum? Actually sum of selected items is an exact sum, so any achievable sum is an integer that is exactly some combination. So the maximum achievable sum <= x is exactly the maximum reachable exact sum <= x. So boolean works. For example, if we have coin 5 and x=6, reachable sums are 0 and 5. Max is 5. That's correct. So boolean DP works.
But careful: In unbounded knapsack, sometimes we can achieve sums that are not exactly any reachable exact sum but dp[j] can be less than j while being an exact sum of some combination, so it's still an exact sum. So it's fine.
Thus boolean DP is simpler.
But there is one optimization: Since we only need max reachable sum, we could early break after x? No.
Implementation details: read input. T test cases. For each, read n, x, then list of n ints. Might be duplicates? Yes, but DP works regardless.
Now, is DP O(n*x) okay? x up to 3000, n up to 3000 -> 9e6 per test. In Python, 9 million iterations is fine; maybe 0.1 seconds? Actually 9 million simple operations might be about 0.2-0.3 seconds depending on environment. With T=10, 90 million operations could be around 2-3 seconds, might still be okay if optimized. But we can also optimize: we can deduplicate coins? If there are duplicate coin values, they are redundant; we can convert to set to reduce n. Since n can be up to 3000, but after dedup, number of distinct coin values is at most 3000 as well, but might reduce a bit. However, we need to consider that having duplicates just adds extra passes that do the same work. So better to convert to set before DP: coins = list(set(A)). But careful: If there are duplicate values, it's fine to use unique; unlimited copies already allow any number, so having multiple copies in the list doesn't give any advantage. So we can deduplicate to speed up. But then we need to ensure that if n is large but many duplicates, dedup helps. However, the worst-case distinct coins = 3000, same as n. So no loss.
Also we can sort coins to maybe break early? Not needed.
Alternatively, we can use bitset operations: maintain a bitset as integer bitmask of reachable sums, and for each coin a, we can left-shift and OR repeatedly for infinite? For unbounded, we can do: reachable |= (reachable << a) while shift within x. But because unlimited, we need to repeat until no change? Actually for infinite coins, the set of reachable sums is the set of all numbers that are linear combinations with non-negative coefficients. That's like the classical coin problem; we can compute using DP: for each a, for i in range(a, x+1): reachable[i] = reachable[i] or reachable[i-a]. That's similar.
Another trick: Since x <= 3000, we could also use BFS/queue to compute all reachable sums <= x. That might be faster? Possibly not.
I'll implement boolean DP with dedup and perhaps use bytearray for speed. In Python, using list of bools is fine. But we can use bytearray (0/1) for faster updates? Actually, Python's list of bools is list of Python bool objects which are ints underneath, but still overhead. bytearray is more memory efficient and can be updated quickly. However, indexing bytearray is also fast. Let's consider using bytearray of length x+1, with 0/1. But then the condition check if dp[i-a] is similar.
We can also break early if we achieve dp[x] = True, then answer is x directly.
Implementation:
def solve():
import sys
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
n = int(next(it)); x = int(next(it))
arr = [int(next(it)) for __ in range(n)]
# deduplicate
coins = list(set(arr))
# we can also filter coins > x because they can't be used? Actually if a > x, it cannot be selected because sum would exceed x. But we can still consider? In DP, we skip because range(a, x+1) empty. So we can filter to speed up.
coins = [c for c in coins if c <= x]
if not coins:
out_lines.append('0')
continue
# maybe sort ascending? not necessary.
dp = bytearray(x+1)
dp[0] = 1
# optionally if any coin == 1 then answer is x (since we can fill exactly x with ones). But not necessary.
for a in coins:
if a == 1:
# can achieve any sum up to x
# then answer = x
# but we need to break out of DP? We can set answer = x and skip rest.
dp[x] = 1 # but we can just note.
# Actually we can set answer = x and break loop early? We need to output x.
# But we still need to skip DP? We can just set answer = x and break, then after loops output.
# However we still need to break out of test case processing.
# We'll handle: if 1 in coins, answer = x.
# So we can check earlier: if 1 in coins -> out_lines.append(str(x)); continue
# We'll do that before DP.
pass
# However, we should do that before DP for speed.
# Actually we already deduped and filtered <=x, so we can check:
# if 1 in coins: answer = x; out_lines.append(str(x)); continue
# Let's implement that optimization.
pass
But careful: if 1 is present, we can achieve any sum from 0 to x, so answer = x. So we can skip DP. That might help in some test cases.
Similarly, if the gcd of coins divides something? Not needed, but we can compute answer by coin change. However, we cannot guarantee that if gcd=1, we can achieve all sums beyond some Frobenius number. But x <= 3000, and coins can be up to 3000. It might be possible that even if gcd=1, we might not be able to achieve x? Actually with unlimited coins and target <= 3000, if there is a coin of value 1, then definitely all sums achievable. If there is no 1, but gcd=1, the Frobenius number for two coins a,b is ab - a - b, which can be large up to ~9e6. However x is only 3000, so it's possible that even if gcd=1, some numbers <=3000 might not be achievable. For example, coins 6,9,20? Actually 6 and 9 have gcd=3, not 1. For gcd=1, e.g., coins 2,3: Frobenius number = 2*3-2-3=1, so all numbers >=2 are achievable? Actually for 2 and 3, achievable sums: 0,2,3,4,5,6,... So all numbers except 1. So 1 not achievable but x could be 1? x>=1, but if x=1 and coins are {2,3}, answer is 0. So with gcd=1, not all numbers <=3000 are achievable; only numbers >= some bound are all achievable. But we cannot easily skip DP just because gcd=1. So only coin 1 gives guarantee.
Hence we will check for coin 1.
Now implement: read all data, process each test case.
Implementation steps:
-
Read all input tokens.
-
t = int(token[0]), pointer.
-
For each test case:
- read n, x.
- read n numbers.
- coins = list(set([a for a in arr if a <= x])) (since >x useless)
- if not coins: answer = 0
- else if 1 in coins: answer = x
- else:
dp = bytearray(x+1)
dp[0] = 1
for a in coins:
for i in range(a, x+1):
if dp[i-a]:
dp[i] = 1
find max i
we can search from x downwards
for i in range(x, -1, -1):
if dp[i]:
answer = i
break
- out_lines.append(str(answer))
-
print("\n".join(out_lines))
This should be efficient.
Testing on sample:
Test case 1: n=3, x=12, coins [1,6,9] (1 present) => answer = 12 -> matches sample? Sample output 12. Good.
But wait, sample output 12: They gave combination 6+6=12, which is achievable. With 1 present, indeed we can also do 12 ones. So answer 12.
Test case 2: n=5, x=9, arr [3,4,4,4,8] => distinct values <=9: {3,4,8} (1 not present). DP: reachable sums: 0,3,4,6 (3+3),7 (3+4),8,9? 9 = 3+3+3, so reachable 9. So answer 9, matches sample.
Works.
Now need to be careful: The DP as written (for a in coins, for i from a to x) with dp[i] = dp[i] or dp[i-a] will consider unlimited uses because we iterate i increasing; when we process a coin, we can use it multiple times because dp[i-a] may have been set in the same loop for a smaller i that used the coin. Example: coin 3, dp[0]=1; i=3: dp[3] = dp[3] or dp[0] => 1; i=6: dp[6] = dp[6] or dp[3] => 1 (since dp[3] was set earlier in the same loop); etc. So correct for unbounded.
But if we have multiple coins, the order doesn't matter.
Now potential improvements: Could we break early if dp[x] becomes true? Then answer = x. So we could check after each coin if dp[x] is 1, then break loops and answer = x. However, we would still need to compute DP? Not necessary; we can break out of the coin loop and then answer = x. That might speed up some cases.
Thus:
for a in coins:
for i in range(a, x+1):
if dp[i-a]:
dp[i] = 1
if dp[x]:
break
After loops, if dp[x] is 1, answer = x; else find max.
But we also have the check for coin 1, which already covers many cases.
But we can also check if x == 0? But x>=1 per constraints? Actually constraints: 1≤x≤3000, so not zero.
Now about input reading: Use sys.stdin.buffer.read() maybe faster.
We'll implement accordingly.
Now let's consider edge cases: All coins > x => no coin <= x, then answer 0. That's correct.
Now time complexity: worst-case: no coin 1 and coins all <=x, and dp[x] never set until end. For each coin a, inner loop from a to x, about x/2 average. So total operations sum over coins of (x - a + 1). If coins are many (like 3000) and each a small (like 1), but we already filter coin 1 and break early. But worst-case, coins are distinct values from 2 to 3000? That would be up to 2999 coins (since 1 not included). Then total iterations roughly: sum_{a=2}^{3000} (3000 - a + 1) = sum_{k=1}^{2999} k = (2999*3000)/2 ≈ 4.5 million. Actually that's per test case if we have all numbers from 2 to 3000. That's less than 9 million. So it's fine.
But we might have up to 3000 coins but many duplicates; after dedup we reduce to distinct ones, so worst-case 3000 distinct. That's fine.
Thus solution is efficient.
But wait: In the DP, we have two nested loops: for each coin a, for i in range(a, x+1). That's O(number_of_coins * x). But if coins are many and a is large, the inner loop is short; so total O(number_of_coins * x) worst-case when many coins are small. For many small coins (like many coins of value 2,3,... but distinct small values) number_of_coins could be up to, say, 3000, but smallest a=1 would have been caught earlier. If smallest a=2, then for a=2, loop runs x-1 ≈ 3000 times; for a=3, ~2998; etc. So total about 3000 * 1500 ≈ 4.5 million, as computed. So worst-case per test case about 4.5 million operations. For 10 test cases: 45 million, which is fine.
Thus the solution should pass easily.
We need to output each answer on a separate line.
Now, one nuance: The problem says: "select numbers from array list(0 or more numbers) such that the sum of these numbers is as close as possible but not exceeding to the sum x. Note:Each element of A can be selected multiple times." So unbounded knapsack.
Hence answer is as described.
Now we must produce the final answer code.
Implementation details:
- Use sys.stdin.read() to read all input.
- Parse tokens as ints.
- Write solve() function.
Edge Cases:
- If there are coins exactly equal to x? DP will set dp[x] = 1, answer = x.
- If coin 1 present, answer = x.
- If coin > x are filtered out.
- If after filtering coins empty (all > x), answer 0.
Now let's test on sample manually.
Test1: n=3,x=12,arr=1,6,9 => coins after filter: [1,6,9] (all ≤12). coin 1 present => answer=12.
Test2: n=5,x=9,arr=3,4,4,4,8 => set = {3,4,8} (8≤9). no 1. DP:
Initialize dp[0]=1.
coin=3: i=3: dp[3]=dp[0]=1; i=6: dp[6]=dp[3]=1; i=9: dp[9]=dp[6]=1. So dp[9]=1.
coin=4: i=4: dp[4]=dp[0]=1; i=5: dp[5]=dp[1]=0; i=6: dp[6] already 1; i=7: dp[7]=dp[3]=1; i=8: dp[8]=dp[4]=1; i=9: dp[9]=dp[5] or current? dp[9] already 1. So fine.
coin=8: i=8: dp[8]=dp[0]=1; i=9: dp[9]=dp[1]=0? but dp[9] already 1.
Finally max i=9 => answer 9.
Works.
Now consider case where no combination gives exact sum but some sum < x: e.g., coins=[2], x=5. Reachable sums: 0,2,4. Max=4. DP yields dp[4]=1. So answer 4. Good.
Now consider case with large x and many coins: fine.
Now we need to ensure we treat multiple test cases correctly.
Now let's produce final code.
But there is another nuance: The DP we are using (for each coin a, for i from a to x) might be slower due to Python's loop overhead. We could micro-optimize: use local variable references, maybe use memoryview? But not needed.
Alternatively, we can use array of bool and use for i in range(a, x+1): if dp[i-a]: dp[i]=True. But using bytearray and check dp[i-a] as integer might be a bit faster: if dp[i-a]: ... because dp[i-a] is 0 or 1, which is truthy. So that's fine.
Potential further optimization: Since we are only ORing, we could use Python's built-in any? Not really.
Now, we need to write final answer.
We'll also include the optimization: if dp[x] becomes true, break out early.
But careful: After we break out of coin loop, we might not have processed all coins, but dp[x] is true; answer = x. So we can set answer = x and skip search.
Implementation:
if 1 in coins:
answer = x
else:
dp = bytearray(x+1)
dp[0] = 1
reached_x = False
for a in coins:
# optional: if a > x: continue (already filtered)
for i in range(a, x+1):
if dp[i-a]:
dp[i] = 1
if i == x:
reached_x = True
break
if reached_x:
break
if reached_x:
answer = x
else:
# find max i
for i in range(x, -1, -1):
if dp[i]:
answer = i
break
But we need to be careful: If we break inner loop when i == x, we might exit before completing all i, but we can break the inner loop using a flag; but simpler: after setting dp[x] to 1, we can break out of both loops; we can use a for-else construct? Or just after inner loop check dp[x]. But we can also just after each coin check if dp[x] and break out of outer loop.
Implementation:
for a in coins:
for i in range(a, x+1):
if dp[i-a]:
dp[i] = 1
if dp[x]:
answer = x
break
else: # executed if not broken
for i in range(x, -1, -1):
if dp[i]:
answer = i
break
But careful: using for-else on outer loop: else executes if loop not broken. That works.
But note: we also have to handle case where coins list is empty; we already handled.
Now, can we further improve by sorting coins? Not needed.
Now produce final code.
We'll write:
import sys
def solve():
data = sys.stdin.buffer.read().split()
if not data:
return
t = int(data[0])
idx = 1
out = []
for _ in range(t):
n = int(data[idx]); x = int(data[idx+1]); idx += 2
arr = list(map(int, data[idx:idx+n])); idx += n
# Filter and deduplicate coins <= x
# Using set comprehension
coins = list({a for a in arr if a <= x})
if not coins:
out.append('0')
continue
if 1 in coins:
out.append(str(x))
continue
# DP
dp = bytearray(x+1)
dp[0] = 1
found_x = False
for a in coins:
# optional: if a > x: continue (already filtered)
for i in range(a, x+1):
if dp[i-a]:
dp[i] = 1
if i == x:
found_x = True
break
if found_x:
break
if found_x:
out.append(str(x))
else:
# find max i where dp[i]==1
# we can loop backwards from x to 0
for i in range(x, -1, -1):
if dp[i]:
out.append(str(i))
break
sys.stdout.write("\n".join(out))
if name == "main":
solve()
Check: In the DP loop, after setting dp[i] = 1, we check if i == x and break inner loop, then set found_x True and break outer. That's fine.
But we can also check after inner loop if dp[x] and break. But using found_x is okay.
Now test with sample input.
We'll simulate:
Input: "2\n3 12\n1 6 9\n5 9\n3 4 4 4 8\n"
After reading tokens: ['2','3','12','1','6','9','5','9','3','4','4','4','8']
Processing first test case: n=3,x=12, arr=[1,6,9]. coins = {1,6,9} (all <=12). 1 in coins -> answer =12, out=['12'].
Second: n=5,x=9, arr=[3,4,4,4,8]. coins = {3,4,8} (all <=9). no 1. dp size 10. dp[0]=1. a=3: loop i=3..9: i=3: dp[0]=1 => dp[3]=1; i=4: dp[1]=0; i=5: dp[2]=0; i=6: dp[3]=1 => dp[6]=1; i=7: dp[4]=0; i=8: dp[5]=0; i=9: dp[6]=1 => dp[9]=1; then after inner, check if dp[x]==1? After loop, dp[9]=1, but we haven't set found_x break? In code, we only break if i==x during inner loop, but we only break when i==x, we set found_x and break inner. In this case i goes 3,4,5,6,7,8,9. At i=9, we set dp[9]=1 and check i==x (9==9) true, then found_x=True, break inner loop. Then after inner loop, we check if found_x: break outer. So we break outer loop. Then found_x True -> answer=9. out becomes ['12','9'].
Works.
Now consider a test where dp[x] never true, e.g., coins=[2], x=5. coins={2}, no 1. dp: a=2, i=2: dp[0]=1 => dp[2]=1; i=3: dp[1]=0; i=4: dp[2]=1 => dp[4]=1; i=5: dp[3]=0; after loop dp[x]=dp[5]=0, found_x remains False. Then after loop (no break), found_x false. Then we find max i: for i from 5 down: i=5 dp[5]=0; i=4 dp[4]=1 => answer=4. out '4'. Works.
Now ensure that we handle case where coins list after dedup includes value 0? But constraints say a_i >=1, so no zero.
Now, about deduplication: using set comprehension is fine.
But note: The DP algorithm for unbounded knapsack using boolean approach requires careful ordering: for each coin a, we iterate i from a to x inclusive. That works as explained.
Alternatively, we could also use the "max sum" DP with integer values: dp[i] = max(dp[i], dp[i-a] + a). That also yields answer. But boolean is fine.
Now check potential pitfalls: When x is large and coins include many duplicates, set reduces to unique values. But what if after filtering there is coin equal to x? Then dp[x] becomes true when we process that coin: i = a = x, dp[0] =1 => dp[x] =1. So answer = x. That is covered by dp[x] detection.
Now, consider case where coin values are not sorted. The DP still works because order doesn't matter.
Now, regarding time: The inner loop uses Python's range and if-check. This is okay.
One might argue that using bytearray and checking dp[i-a] is slower than using list of bool? Actually, bytearray is efficient. Might be fine.
Now, is there any possibility of overflow or memory? x <= 3000, so dp size 3001, trivial.
Now, we must ensure we correctly output each answer on new line.
Now, let's consider another test: T=1, n=3000, x=3000, arr contains all numbers from 1 to 3000 (including 1). Then we would detect 1 and answer x quickly, so fast.
If no 1, but many numbers, DP loops as described.
Thus solution should be accepted.
Now produce final answer with explanation? The user asks "Write a python solution". So just the code.
But we need to include proper imports and function definition.
I'll output final code.
But before final, I should double-check reading input: using sys.stdin.buffer.read().split() gives bytes; converting to int via int() works because bytes are convertible. But we need to decode? Actually, int(b'123') works in Python? Let's test: int(b'123') returns 123. So it's fine. Alternatively, we can decode to str but not needed.
We should be careful: The tokens are bytes, but int() can take bytes in Python3. So it's okay.
Now, final code.
One more optimization: Since we already filtered coins <= x, the inner loop for each a will always have i from a to x inclusive. That's fine.
Now, confirm that dedup set does not preserve order, but not needed.
Now, let's also consider the possibility of having coin value 0? Not per constraints.
Now, what about case where no coin selected? That yields sum 0, always possible.
Now, final code is ready.
But maybe we can reduce memory and time further by using bitset with integer: initialize reachable as 1 (bit 0 set). For each coin a, we can update reachable = reachable | (reachable << a) and then mask to x bits. But we need to apply repeatedly for unbounded? Actually, (reachable << a) will include sums that add one coin a to previously reachable sums, but if we do it only once, we only allow at most one use of each coin. For unlimited, we need to do repeated shifts until no change? For coin change with unlimited coins, we can do: for a in coins: for i in range(a, x+1): reachable[i] |= reachable[i-a]. That's essentially the same as DP loop. Bitset shifting with OR in a loop could be faster if we use Python's integers as bitsets and use while loop? But for x up to 3000, integer bitset would be 3001 bits, about 375 bytes, and we could apply: for a in coins: for shift in range(a, x+1): reachable |= (reachable << a) but that would add multiple copies? Actually, to get unbounded, we can do: for a in coins: for i in range(a, x+1): if (reachable >> (i-a)) & 1: set bit i. That's similar to DP but using bit operations might be faster? However, Python's big integer bit operations are fast but the loop over i would still be needed. A typical optimization for unbounded knapsack with bitset is: reachable = 1; for a in coins: reachable = reachable | (reachable << a) # but this only allows at most one of each coin? Actually, if you do that once, you can only take each coin at most once because you shift the current reachable set by a, and OR. Starting from only 0, after one shift you get sums that are exactly a (one copy). After OR, you have {0, a}. If you then shift by a again? But you are not applying it repeatedly. However, if you iterate over the same coin multiple times, you effectively allow unlimited uses. So you could do: for a in coins: for _ in range(x // a): reachable |= (reachable << a) but that would be many iterations. The standard approach for unbounded coin change (subset sum) using bitset is to use a while loop: reachable_new = reachable; while (reachable_new << a) & mask != 0: reachable_new |= (reachable_new << a) ??? That's complicated. So better to stick with simple DP.
Given constraints, simple DP is fine.
Now, confirm that the solution prints correct output for sample.
Now, write final answer. ```python
import sys
def solve() -> None:
data = sys.stdin.buffer.read().split()
if not data:
return
t = int(data[0])
idx = 1
out_lines = []
for _ in range(t):
n = int(data[idx])
x = int(data[idx + 1])
idx += 2
arr = list(map(int, data[idx:idx + n]))
idx += n
# keep only coins that can be used (value <= x) and remove duplicates
coins = list({v for v in arr if v <= x})
# edge cases
if not coins:
out_lines.append('0')
continue
if 1 in coins:
out_lines.append(str(x))
continue
# dp[i] == 1 means sum i can be formed exactly
dp = bytearray(x + 1)
dp[0] = 1
found_x = False
for a in coins:
# unlimited use of coin a – iterate forward
for i in range(a, x + 1):
if dp[i - a]:
dp[i] = 1
if i == x:
found_x = True
break
if found_x:
break
if found_x:
out_lines.append(str(x))
else:
# find the largest achievable sum ≤ x
for i in range(x, -1, -1):
if dp[i]:
out_lines.append(str(i))
break
sys.stdout.write('\n'.join(out_lines))
if name == "main":
solve()