You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers.
More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The value of such an arrangement is (x1 - x2) + (x2 - x3) + ... + (xn - 1 - xn).
Find the largest possible value of an arrangement. Then, output the lexicographically smallest sequence x that corresponds to an arrangement of the largest possible value.
Input
The first line of the input contains integer n (2 ≤ n ≤ 100). The second line contains n space-separated integers a1, a2, ..., an (|ai| ≤ 1000).
Output
Print the required sequence x1, x2, ..., xn. Sequence x should be the lexicographically smallest permutation of a that corresponds to an arrangement of the largest possible value.
Examples
Input
5
100 -100 50 0 -50
Output
100 -50 0 50 -100
Note
In the sample test case, the value of the output arrangement is (100 - ( - 50)) + (( - 50) - 0) + (0 - 50) + (50 - ( - 100)) = 200. No other arrangement has a larger value, and among all arrangements with the value of 200, the output arrangement is the lexicographically smallest one.
Sequence x1, x2, ... , xp is lexicographically smaller than sequence y1, y2, ... , yp if there exists an integer r (0 ≤ r < p) such that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to arrange n integers to maximize sum of differences between adjacent integers: V = (x1 - x2) + (x2 - x3) + ... + (x_{n-1} - x_n). This simplifies telescoping? Let's compute:
Because all intermediate terms cancel: x1 - x2 + x2 - x3 ... + x_{n-1} - x_n = x1 - x_n. Indeed, each x_k for k=2..n-1 appears once as + (x_{k-1} - x_k) gives -x_k, and in next term + (x_k - x_{k+1}) gives + x_k, cancel. So V = x1 - x_n.
Thus maximizing V is simply maximizing (first element minus last element). So we need to choose first element as large as possible and last element as small as possible. But we must also consider that we can permute the numbers arbitrarily. So maximum possible V = max_i a_i - min_i a_i. That's the maximum difference. However, careful: Is it always achievable? Yes, we can place the maximum element at the beginning and the minimum at the end. But need to check: Could there be other constraints? Since V = x1 - x_n, only first and last matter. So indeed the maximum value is max(a) - min(a). That is obvious.
But the problem wants the lexicographically smallest permutation among all arrangements that achieve this maximum value. So we need to construct a permutation of the given numbers (multiset) with x1 - x_n = max - min, and among those, lexicographically smallest.
Lexicographically smallest sequence x1, x2, ..., xn means we need to minimize x1 first, then if tie minimize x2, etc. Wait, "lexicographically smallest" usually means compare sequences element by element, and the smaller element at the first differing position makes the sequence smaller. So we want the smallest possible x1, then smallest possible x2 given x1 fixed, etc. However, we have a constraint: the arrangement must achieve maximum V, i.e., x1 - x_n = max - min.
But note: max and min are fixed from the array. We have multiple copies? Possibly duplicates. So we need to consider multiset.
Let M = maximum element in a; m = minimum element in a. We need x1 - x_n = M - m. That implies x1 is the maximum and x_n is the minimum? Let's see: Since x1 ≤ M (as M is max overall) and x_n ≥ m (as m is min overall), the difference x1 - x_n can be at most M - m. To achieve exactly M - m, we need x1 = M and x_n = m. Because if x1 < M, then even if x_n = m, the difference is less than M - m. Similarly if x_n > m, difference is less. So indeed, for the maximum value, we must place the maximum element at the first position and the minimum element at the last position. That's necessary.
But careful: If there are multiple occurrences of maximum and minimum, we could choose any occurrence. For example, if there are multiple maximum values, then x1 can be any of those max values, but then x_n must be a minimum element (any of the mins). However, if there are multiple max, we can choose the smallest possible x1? Actually x1 would be M (the max). All max values are equal, so x1 is the same value regardless of which copy we pick. Similarly, x_n = m. So lexicographically, the first element is M (a fixed number). So that doesn't allow to minimize further; but if there are multiple identical max values, we might still have choices for other positions.
Thus the arrangement must have first element = M and last element = m.
Now we need to arrange the remaining n-2 elements (which are all the original numbers except one copy of M and one copy of m) in positions 2 to n-1 in some order, to achieve lexicographically smallest overall sequence. Since the value V does not depend on the internal arrangement (since telescoping to x1 - x_n), any ordering of the middle elements yields the same total value. So we are free to arrange them arbitrarily, as long as first is M and last is m. But we must consider that lexicographic order: we want the smallest sequence x1, x2, ..., xn. x1 is fixed as M. Now we need to choose x2 as small as possible, then x3 as small as possible given x2, etc., while still having the property that the last element is m. But note: The last element is forced to be m, but the ordering of middle elements might affect the ability to have m at the last position? Yes, we can place m at the last, but we must ensure that we use exactly one m (if there are multiple minimums, we need to keep at least one for the last; we can use other mins in the middle if duplicates). However, we have to consider if we have multiple m values; we need to place at least one m at the end, but we might have other mins placed earlier. Similarly for M, we need exactly one M at the start, but duplicates can be placed elsewhere.
Thus the problem reduces to: Given multiset of numbers, we want to construct a permutation such that:
x1 = M (the maximum element of the original multiset)
x_n = m (the minimum element of the original multiset)
The sequence is lexicographically smallest.
Because any such sequence yields the maximum value.
But is there any hidden constraint? Since the value is x1 - x_n, if there are duplicates of M and m, could we achieve the same maximum by having x1 = M and x_n = m but maybe using a different copy? Still same. So the condition is exactly that.
Thus we need to output the lexicographically smallest permutation among those with first element max and last element min.
However, we must consider the case where max = min? If all numbers equal, then max - min = 0, and any permutation yields that value. Then the maximum value is 0. But then x1 - x_n = 0, so we don't need x1 = max and x_n = min? Since max = min, then x1 = max and x_n = min would be x1 = value, x_n = same value, difference 0. But could we achieve 0 with other choices? If all numbers equal, any x1, x_n are same value, so x1 - x_n = 0 regardless. So the condition "x1 = max and x_n = min" is automatically satisfied for any permutation because all numbers equal max = min. So we need to consider that case separately. Actually if all numbers equal, then the set has all same values. Then the lexicographically smallest permutation is to sort the numbers ascending? Since all are equal, any order yields the same sequence. But to be precise, the lexicographically smallest permutation of a multiset of equal numbers is just the numbers in any order (they are identical). But we need to output some permutation. Typically, the lexicographically smallest permutation of an array is the sorted ascending order. Since all numbers are equal, sorted ascending is same. So we can just output the numbers sorted ascending. But note that we want lexicographically smallest overall. Since all numbers are identical, any sequence is identical element-wise, so they are all equal, so any is fine. But we can adopt a generic algorithm that works.
If not all equal, then we have distinct max and min (or maybe max = min? Already handled). So we need to produce the lexicographically smallest sequence with x1 = max, x_n = min. The rest can be arranged arbitrarily. To get lexicographically smallest, we would want the smallest possible x2, then x3, etc., while respecting that we must place the min at the end. But note: We cannot place the min anywhere else except the last? Actually we can have other min values (if duplicates) in the middle, but the last must be a min. If there are multiple min values, we can place one at the end and the others anywhere. Similarly for max: we can have duplicates of max; they can appear in the middle. But we need x1 = max. So we must reserve one max for position 1, and one min for position n.
Now, to minimize lexicographically, after fixing x1 = max, we want x2 to be as small as possible. However, we must also ensure that we can arrange the remaining elements (including possibly the min) such that x_n ends up being min. Since we have control over ordering, we can always put min at the end, regardless of what we put in positions 2..n-1. The only potential issue is if we use all min elements earlier, leaving none for the last. But if there is only one min and we put it somewhere else, then last would not be min. So we must guarantee that at least one min remains for the last position.
Thus, when choosing x2, x3, ..., x_{n-1}, we must leave at least one copy of min to place at last. If there is only one occurrence of min, then we must not place any min before position n. So x2 cannot be min if min is unique and we need it at the end. Similarly, if there are multiple mins, we can place some mins earlier, as long as at least one remains for the end.
Similarly, for max, we must use one max at position 1; duplicates can be placed elsewhere.
Therefore, the problem becomes: We have a multiset S of numbers, we need to produce a permutation such that:
first = max(S)
last = min(S)
The sequence is lexicographically smallest.
We can approach by constructing the sequence greedily: from position 1 to n, choose the smallest possible element that can be placed at that position while still being able to complete the permutation satisfying the constraints.
This is reminiscent of constructing lexicographically smallest sequence under constraints that certain elements must be at certain positions (like last must be min). Since n is small (≤100), we can use a backtracking or simply a greedy with feasibility check.
But we might find a direct construction. Let's think.
We need to place max at first. So x1 = M.
Now we need to fill positions 2..n-1 with the remaining numbers (the multiset minus one M and one m), but we also need to consider that the last position (n) is forced to be m. Actually we can consider that we are building the sequence from left to right, and we must reserve one m for the last position. So during construction of positions 2..n-1, we must ensure that after placing some elements, we still have at least one m left (unless we are at position n and we place it). So for positions i from 2 to n-1, we can choose any element from the remaining multiset except that we cannot take the last copy of m if that would leave no m for the last. Similarly, we might also need to consider that we have to place max at first, but we already did.
Thus, the lexicographically smallest sequence is obtained by: starting at i=2, we try the smallest available number that doesn't make it impossible to fill the remaining positions under the constraint that eventually last must be m. Since the only constraint is that at the end we need to have m, the feasibility check is simply: after picking an element at position i, we need to ensure that the number of remaining positions (including the last) is at least the count of remaining elements? Actually we just need to ensure that we can place m at the last. That is, after picking, we must have at least one m left if there are still positions to fill that require m at last. But the last position is the only forced one. So we need to guarantee that when we reach position n, we have exactly one m left. So throughout, we need to keep the invariant: number of m's remaining >= 1 until we get to position n, where we place it. Also, we need to be able to place the rest arbitrarily, which is always possible as long as we have enough elements. There is no other constraint. So essentially, we can treat it as we have to output the lexicographically smallest permutation such that the last element is m. But also the first is M? Actually we already set first=M, so we remove one M. So we have to start with M. Then from positions 2 to n-1, we can choose any numbers, but must keep at least one m for the end. So it's similar to: we have a multiset T = original with one M removed, but we still have all min copies. Actually we removed one M, but we haven't removed m yet; we need to reserve one m for last. So when constructing positions 2..n-1, we have the multiset R = original minus one M (since we used one M) but we still need to reserve at least one m. So we can consider we have R = original without the used M. At the end, position n will be m, so we need to ensure we leave one m.
Thus, we can simply: after fixing x1=M, we want to arrange the remaining n-1 elements in positions 2..n in lexicographically smallest order given that the last element must be m. But note: the lexicographic order compares the whole sequence including x1; after x1 fixed, we compare x2, x3, ..., xn. So we need to minimize x2, then x3, etc., under the constraint that x_n = m.
Thus the problem reduces to: Given a multiset of n-1 numbers (the original with one M removed), we need to order them into a sequence of length n-1 (positions 2..n) such that the last element (position n) is m, and the sequence is lexicographically smallest. That is a classic problem: smallest lexicographic sequence with a fixed last element.
We can approach by constructing the sequence from left to right for positions 2 to n-1, and at the end put m. For each position i from 2 to n-1, we choose the smallest possible element from the remaining multiset that does not make it impossible to eventually place m at the end. The only impossibility is if we use up all copies of m before the last position. So as long as we keep at least one copy of m for the last, we can place anything else. So the greedy is: at each step, consider the multiset of remaining numbers (including all m copies except those used). If the smallest element in the multiset is not the last remaining m (i.e., if after taking it, we still have at least one m left), then we can take it. If the smallest element is m, but we have more than one copy of m, we can still take it, because we will still have at least one m left for the end. If the smallest element is m and it's the only copy left, then we cannot take it now because we need to save it for the last position. In that case, we must take the next smallest element available.
That greedy yields the lexicographically smallest sequence under the constraint that the last element is m.
But we also have the constraint that the first element is M. Since M is the max, and we have removed one copy, it's possible that M itself might appear again in the remaining multiset if there were duplicates. That's fine.
So algorithm:
Read n and array a.
Compute M = max(a), m = min(a).
If M == m (all equal): just output a sorted ascending (or any but sorted is fine). Since all equal, any permutation is same; sorted is lexicographically smallest (though they are all identical). We'll handle it uniformly.
Actually our greedy will also work? Let's test: M == m. Then we need x1 = M (which is the value) and x_n = m (same). But we must also ensure that we have one M at first and one m at last. If all numbers are equal, we can just set x1 = that value, and the rest any order, with last also that value. Lexicographically smallest sequence would be all elements the same, so any order yields same sequence. But we must be careful: The greedy described might fail because after taking one element for first, we have remaining n-1 elements all equal to the same value. Then we want to fill positions 2..n with the constraint that last must be m. Since all elements are m, it's fine. But the greedy: we have multiset of n-1 copies of value v. We need last to be v. At position 2, the smallest element is v, but if we take it, we will have n-2 copies left, still at least one for last, so it's allowed. So we take v. Then we continue taking v each time. So the sequence becomes [v, v, v, ..., v] which is lexicographically smallest (all same). That works. So the greedy works even when M == m, but we must ensure that we have at least one m left; since we initially have n-1 copies, we can take all but one. So it's fine.
But we must also consider that we removed one M for first position. If all numbers equal, we have n copies of v. After using one for x1, we have n-1 copies left. Since we need x_n = v, we will have at least one copy left at the end. So greedy works.
However, note: In the case M != m, the greedy might still be valid.
Thus the overall algorithm is:
Create a multiset (e.g., list) of the numbers.
Remove one occurrence of M (the max) for x1. But careful: There might be multiple occurrences of M. For lexicographic smallest, does it matter which copy we remove? Since all copies identical, any is fine. So we can just remove one occurrence of M from the list.
Now we have a multiset R of size n-1. We need to produce a sequence of length n-1 (positions 2..n) with the constraint that the last element must be m (the minimum). And we want lexicographically smallest sequence from positions 2 onward. However, note that the whole sequence includes x1 already fixed. So we just need to generate positions 2..n lexicographically smallest given that last = m.
We'll generate positions 2 to n-1 greedily, then set position n = m.
Greedy for positions 2..n-1:
Initialize an array result[1..n] (1-indexed). Set result[1] = M.
Let multiset R be the list of remaining numbers (including possibly m and M copies). Let count_m_in_R = number of m in R.
We need to ensure that after constructing positions 2..n-1, we have exactly one m left to place at position n. So we must maintain that at any step before position n, we have at least one m remaining.
For i from 2 to n-1:
Among the elements in R, consider the smallest element.
If that smallest element is m and count_m_in_R == 1 (i.e., it's the only remaining m), then we cannot take it because we need to save it for last. So we must take the next smallest element (i.e., the smallest element greater than m).
Otherwise, we can take that smallest element (even if it is m but there are multiple copies, we can take one, reducing count_m_in_R by 1).
Remove that chosen element from R (and update count_m_in_R if it's m).
Set result[i] = chosen element.
After finishing i = n-1, we will have R containing exactly one element? Actually we have removed (n-2) elements for positions 2..n-1, so R should contain (n-1) - (n-2) = 1 element left. That element must be m (since we preserved at least one m, and it's the only element left). However, we need to verify that the greedy ensures that the remaining element is indeed m. Because we might have taken all m copies earlier if there were multiple; but as long as we always kept at least one m, the last remaining could be m or something else? At the end, we have exactly one element left. Since we ensured that at least one m remains throughout, and all other elements might have been taken, the final element could be m. But it could also be something else if there were other numbers left? Wait: The total number of elements left after position 1 is n-1. We fill positions 2 to n-1, which is (n-2) positions. So we will remove (n-2) elements from R. So one element remains for position n. If we always ensure that at least one m remains in R, then the final element will be that m? Not necessarily: It could be that we have other elements also remaining along with the m at the last step? But we remove exactly n-2 elements, leaving 1 element. So if we ensure that at any point, we have at least one m, then at the moment when only one element remains, that element could be m or it could be some other element if we haven't taken it, but if there are other elements besides m, they could also be left. But we need the final element to be exactly m. The greedy algorithm as described only ensures we don't take the last m prematurely. But it doesn't guarantee that when we have only one element left, it is m; it could be another element if we haven't taken it and we saved m but also saved another element. However, we have control: we are constructing positions 2..n-1 by picking elements. At each step, we decide which element to take. The goal is to end with exactly one element, which we want to be m. So we need to ensure that after we have taken n-2 elements, the only remaining element is m. Is that automatically guaranteed if we never take the last m? Not exactly: Suppose we have R = {m, a, b} with n-1=3, positions 2 and 3 (since n=4? Let's test: n=4, after x1=M, R size 3. Need positions 2,3,4 with last=m. So we need to fill positions 2 and 3 (n-2=2) and leave one for position 4. Greedy: i=2: smallest element is m, but count_m=1 -> cannot take m, so take next smallest a. Remove a. R={m,b}. i=3: smallest is m, count_m=1, but note: this is position 3, which is not the last? Actually we are at i=3? Since n=4, positions: 1(M),2,3,4. So we need to fill positions 2 and 3. i goes from 2 to n-1 = 3. At i=3, we are at the second of the two middle positions. At this point, we have R={m,b}. We still need to place position 3 (i=3) and then position 4 (last). We have to choose element for position 3. We must ensure that after taking position 3, the remaining element is m. So at i=3, we cannot take m because then the last would be b, not m. So we must take b. The greedy rule: smallest element is m, count_m=1, so we skip m and take next smallest b. That's correct. After removing b, R={m}, set position 3 = b. Then position 4 = m. So it works.
Now consider a scenario with multiple m's: R has two m's and one a. n=5 -> after x1, R size 4. Need positions 2,3,4,5 with last=m. So positions 2,3,4 (n-2=3) to fill. Greedy: i=2: smallest is m, count_m=2 >1, so can take m. Remove one m, count_m becomes 1. R = {m, a, ?} Actually original R: two m's and a, say values: m, m, a. After taking one m: R = {m, a}? Wait originally R size 4? Actually n=5 means total numbers 5. After using one M for x1, remaining 4 numbers. Suppose they are: m, m, a, b (maybe but I said two m's and one a, but need 4 numbers: two m's, a, b? Let's adjust: to illustrate potential problem, need at least one non-m that might be left if we don't manage properly. But if we have multiple m's, we can take m early. At the end, the remaining must be an m. That's possible if we leave at least one m. The greedy algorithm will always take the smallest available as long as it is not the last m. At some point when only one m remains, we will avoid taking it unless it's the last position. So the final remaining will be m, because if there are other elements, we will take them before we are forced to take the last m, as we will skip the last m until the very end. But what if there is an element smaller than the last m? Actually m is the minimum, so all other elements are >= m. So the smallest element is always m if any m remains. So when only one m and some other elements remain, the smallest is m, but we skip it because it's the last m. So we take the next smallest (which is larger). This reduces the other elements, leaving the m untouched. Eventually, we will have only m left. So final element will be m. So greedy works.
Thus the greedy algorithm is correct.
But we must also consider the case where there is only one m in the original multiset. Then after using x1=M, the remaining multiset R contains exactly one m. The greedy will never pick that m until the last position, because at any step before the last, if we try to pick smallest, it is m but count_m=1, so we skip it and pick the next smallest. So the m stays until the end. Good.
Now about M duplicates: If there are multiple M's, after using one for x1, the remaining R may contain additional M's. The greedy might pick them if they are the smallest? But M is the maximum, so it's the largest. So it will never be the smallest among remaining unless all remaining are M (i.e., all numbers equal, which we already covered). In typical case with distinct max and min, M > other numbers, so it's the largest. So it will never be chosen early because we always pick the smallest possible. So the remaining M's will be placed later, likely near the end, except we avoid last because last must be m. But can an M end up at position n? No, because position n is forced to m. So the remaining M's will be placed in positions 2..n-1 if they are the only choices left after we have taken all smaller numbers. That is fine.
Now we must check that the lexicographically smallest sequence indeed matches this greedy. Because we want to minimize x2 first. The greedy picks the smallest possible element that can be placed at position 2 while still allowing a valid completion. This is a standard lexicographic minimization: at each step, pick the smallest candidate that allows a feasible completion. Since the only feasibility constraint is that the last element must be m, the greedy as described is optimal. We can prove by exchange argument: Suppose there is an optimal lexicographically smallest sequence. At position 2, if there exists a smaller element that can be placed without making it impossible, then we could replace the element at position 2 with that smaller one and rearrange the rest to satisfy the last=m constraint, resulting in a lexicographically smaller sequence. The greedy ensures we pick the smallest such.
So algorithm: Use a data structure to get smallest element from multiset efficiently. Since n ≤ 100, we can simply use a list and sort, and then simulate by scanning for the smallest candidate each time. For each position i from 2 to n-1:
Sort the remaining list (or maintain a multiset). Actually we can keep a sorted list and update by removing an element; n small, O(n^2) is fine.
Approach:
Count frequencies using dictionary or just list.
Let remaining = sorted list of the n-1 numbers after removing one max. We need to keep track of the count of m.
But careful: When we remove one max, we need to ensure we remove a max, not just any max? If there are multiple max, we remove exactly one occurrence. The choice doesn't matter.
Implementation steps:
Read n, array a.
Compute M = max(a), m = min(a).
Create a list or multiset of a. We'll use a list rem = copy of a.
Remove one occurrence of M from rem (find and delete).
Also, we need to know the count of m in rem. But note: m might be equal to M if all equal. But then after removing one M, we have n-1 numbers all equal to m. So m count = n-1.
Now we want to construct the sequence:
result[0] = M (assuming 0-indexed output list).
We need to fill result[1] to result[n-2] (i.e., positions 2..n-1 in 1-indexed) using greedy, and result[n-1] = m.
But careful: result[n-1] will be set to m at the end, but we must ensure that the m we put is the reserved one. However, there might be multiple m's; we can just set result[n-1] = m, and we need to remove one m from rem at the end. But the greedy will also potentially remove m's if allowed. So we need to incorporate the fact that we must leave exactly one m for the end. So we can treat the process as: we have rem (size n-1) that includes all numbers except the initial M. We need to select n-2 elements to place in positions 1..n-2 (0-indexed after first) (i.e., positions 2..n-1) such that we leave exactly one m for the last position. So we can treat the last m as not in rem until we assign it. But we can also keep it in rem and enforce not to use the last copy. It's easier to keep rem and at each step, when selecting, we avoid taking the last m.
Implementation:
Let rem be a multiset (list) of the n-1 numbers.
Let count_m = number of times m appears in rem.
For i in range(1, n-1): # i indexes result[1] to result[n-2] inclusive, total n-2 positions.
Sort rem (or maintain sorted order) to find the smallest element.
If the smallest element is m and count_m == 1:
then we cannot take m; we need to take the next smallest element.
So we find the smallest element that is > m.
else:
we take the smallest element.
Remove that chosen element from rem (and decrement count_m if it is m).
result[i] = chosen.
After loop, rem should have exactly 1 element, which should be m (since we preserved at least one m). Set result[n-1] = that element.
But we need to ensure that after the loop, rem indeed has size 1. It will because we removed n-2 elements from rem of size n-1.
Edge cases:
n=2. Then after x1 = M, we have rem size 1. We need to fill positions 2..n? Actually with n=2, we have positions 1 and 2. x1 = M, x2 must be m to achieve max value. So result = [M, m]. Our algorithm: rem = original minus one M -> should contain exactly m (assuming M != m). But what if there are duplicates? If M and m are equal (all equal), then after removing one M, rem contains the other element which is also M. But we need x2 = m, which equals M. So it's fine. Now our loop: i from 1 to n-1 = 1? Since n=2, n-1=1, range(1, n-1) = range(1,1) empty. So we skip loop. Then we set result[1] = the only element in rem. That works.
Check duplicate m and M properly: Suppose there are multiple m's. Then after removing one M, rem includes multiple m's. The greedy will take m's early as long as count_m > 1. At the end, we'll have one m left and set as last. That's fine.
Suppose there are multiple M's. After removing one M, rem includes other M's. Since M is the max, it will be the largest. The greedy picks smallest elements first, so M's will not be taken until maybe later if only M's remain. However, there is a scenario: after removing all smaller numbers, at some point the remaining elements might be several M's and one m. But we cannot take m if it's the last copy, so we would need to take an M. But M is larger than m, so it is not the smallest; the smallest is m, but we skip it. So we take the next smallest, which could be an M if all others are M? Actually if we have remaining: one m and several M's, then the smallest is m, but count_m=1 so we skip m, next smallest is M (since M > m). So we take an M. That's allowed. Then after taking some M's, eventually we might have only m left. So final is m. Works.
Now need to confirm that the resulting sequence indeed has x1 = M and x_n = m and is lexicographically smallest. We can test with examples.
Example: Input: 5
100 -100 50 0 -50
M=100, m=-100.
After removing one 100, rem = [-100, 50, 0, -50] (size 4). count_m = count of -100 = 1.
Now positions: result[0]=100.
Loop i=1 to 3 (since n-1=4, range(1,4) yields i=1,2,3). We'll fill result[1], result[2], result[3].
rem sorted: [-100, -50, 0, 50]
i=1: smallest = -100, but count_m=1 => skip, so take next smallest = -50. Remove -50, result[1] = -50. count_m unchanged.
rem now = [-100, 0, 50] sorted.
i=2: smallest = -100, count_m=1 => skip, take next smallest = 0. Remove 0, result[2] = 0.
rem = [-100, 50].
i=3: smallest = -100, count_m=1 => skip, take next smallest = 50. Remove 50, result[3] = 50.
Now rem = [-100] (only m). Set result[4] = -100.
Sequence: [100, -50, 0, 50, -100] matches output.
Now test a case with multiple mins: Suppose a = [5,1,1,2] n=4. M=5, m=1.
After remove one 5, rem = [1,1,2]. count_m=2.
Result[0]=5.
Loop i=1 to 2 (i=1,2):
rem sorted: [1,1,2]
i=1: smallest =1, count_m=2>1 => can take. Remove 1, result[1]=1, count_m=1.
rem = [1,2].
i=2: smallest =1, count_m=1 => skip, take next smallest =2. Remove 2, result[2]=2.
rem = [1]. Set result[3]=1.
Sequence: [5,1,2,1]. Is that lexicographically smallest? Let's consider alternative: Could we have [5,1,1,2]? That would have last=2 not 1, so invalid because last must be m=1. Another: [5,2,1,1] -> compare lex: x1=5 same, x2: 1 vs 2, 1 is smaller, so [5,1,2,1] is smaller. Could we have [5,1,1,1]? Only one 5? Actually numbers: 5,1,1,2. So only two 1's. So [5,1,1,2] invalid last=2. [5,2,1,1] x2=2 larger. So [5,1,2,1] seems smallest. Good.
Now test with multiple max: a = [10,10,1,2] n=4. M=10, m=1.
After removing one 10, rem = [10,1,2]. count_m=1 (only one 1). Result[0]=10.
i=1 to 2:
rem sorted: [1,2,10]
i=1: smallest=1, count_m=1 => skip, take next smallest=2. Remove 2, result[1]=2.
rem=[1,10].
i=2: smallest=1, count_m=1 => skip, take next smallest=10. Remove 10, result[2]=10.
rem=[1], result[3]=1.
Sequence: [10,2,10,1]. Compare alternative: [10,10,2,1]? That would have x2=10 >2, so lex larger. [10,1,10,2]? last=2 not 1 invalid. So our result is lex smallest.
Now test with all equal: a = [3,3,3] n=3. M=3,m=3.
Remove one 3: rem=[3,3]. count_m=2 (since m=3).
Result[0]=3.
Loop i=1 to n-2? n=3 => n-1=2, range(1,2) gives i=1 only.
rem sorted: [3,3]
i=1: smallest=3, count_m=2>1 => can take. Remove one 3, result[1]=3, count_m=1.
rem=[3]. Set result[2]=3.
Sequence: [3,3,3]. Lex smallest is all 3s.
Now test with M and m distinct but rem has multiple m and also some numbers equal to m? But m is min, so all equal to m are mins.
Now check a scenario where the smallest element is not m? Actually m is the global minimum, so the smallest element in rem will always be at least m, and exactly m if any remain.
Thus greedy works.
But we must also consider the possibility that after removing one M, the multiset rem may not contain any m? That cannot happen because m is the minimum overall; if we remove M, we still have at least one m (since m is not necessarily removed unless m = M, which is the all equal case, but then m = M, and we remove one M, but there may still be m? Actually if all equal, m=M, after removing one M, we still have copies of m (since there were n copies). So rem always contains at least one m? In case of distinct M and m, m is not equal to M, so we didn't remove m. So rem contains at least one m. So safe.
Now we should verify if there is any nuance: The problem statement: "Find the largest possible value of an arrangement. Then, output the lexicographically smallest sequence x that corresponds to an arrangement of the largest possible value." Since V = x1 - x_n, maximum is M - m. But is it possible that there are multiple arrangements achieving M - m that do not have x1 = M and x_n = m? Let's double-check: We need x1 - x_n = M - m. Since x1 ≤ M and x_n ≥ m, the maximum possible difference is M - m. To achieve that, we must have x1 = M and x_n = m simultaneously. Because if x1 < M, then even with x_n = m, difference < M - m. If x_n > m, difference < M - m. So both equalities are necessary. So yes.
Thus our approach stands.
Now what about the case where there are multiple copies of M and m? We need to ensure we are using one of each at the ends. That's what we do.
Now the lexicographically smallest sequence overall with x1 = M and x_n = m: Since x1 is fixed at M, the next element we want to minimize. Our greedy does that.
Potential corner: Suppose the smallest element after M is something like m but there is only one m, so we cannot take it. Then we take the next smallest. That yields minimal x2.
Now consider if there are no other elements besides the mandatory m? That's n=2 case handled.
Now complexity fine.
Implementation details:
We need to handle removal of one M from the list. Since there may be multiple M, we can simply find one occurrence and remove it. In Python, we can do:
lst = a[:]
lst.remove(M) # removes first occurrence
But careful: If M == m and we remove one M, that's fine.
Now we need to keep rem as a list that we will modify. For each iteration, we need to find the smallest element, and if smallest is m and count_m == 1, we need the next smallest. Instead of sorting the entire list each time (which is O(n^2 log n) but n=100, fine), we can sort rem once and maintain it as a sorted list, but removal would require O(n) to maintain sorted order. Since n is small, we can simply sort each time O(n log n) per iteration, total O(n^2 log n) is fine. Or we can use a multiset like collections.Counter and generate the sorted order by iterating from min to max? But n small, simplicity is best.
But careful: When we sort, we need to know the current multiset. We could just keep a list rem and each iteration:
Sort rem.
Find the index of the element to take:
If the first element (smallest) is m and count_m == 1, then we need the second smallest (the next element that is not the only m). But there could be duplicates: e.g., rem = [m, m, x,...], count_m=2, smallest = m, but we can take m. So we need to compute count_m from the list or maintain variable. We'll maintain a variable count_m that tracks the number of occurrences of m in rem.
So algorithm:
At start: rem = list after removal; count_m = rem.count(m).
For i in range(1, n-1):
Sort rem.
candidate = rem[0] # smallest
if candidate == m and count_m == 1:
candidate = rem[1] # but careful: rem[1] might also be m if count_m >1? Actually if count_m ==1, there is exactly one m, so it will be at some position. After sorting, rem[0] is that m (since it's the smallest). Then rem[1] must be > m (since only one m). So candidate = rem[1] is safe. However, what if rem length is 1? But we only enter loop when n-1 >=2? Actually we loop for i from 1 to n-2 inclusive. So when we are at the last iteration before setting last, rem size will be >=2? At the start of loop for i = n-2? Let's examine: before the loop, rem size = n-1. Each iteration removes one element, so before iteration i, rem size = (n-1) - (i-1). The loop runs for i=1,..., n-2, so before the last iteration (i = n-2), rem size = (n-1) - ((n-2)-1) = (n-1) - (n-3) = 2. So there will be at least 2 elements in rem at the start of each iteration. So rem[1] exists. Good.
else candidate = rem[0].
Remove candidate from rem (list remove first occurrence; we need to remove exactly that value; since list may have duplicates, we can remove by value using rem.remove(candidate) which removes the first occurrence. But careful: If candidate is not the first element? In sorted list, the first occurrence of candidate might not be at index 0 if there are duplicates? Actually if we sort, then rem[0] is the smallest. If we want to remove that specific element, we can do rem.pop(index) where index is 0 if we take the smallest, or 1 if we take the second smallest. That is more precise: Instead of using remove, we can directly pop the index. Because we know the index. So we can:
if condition:
idx = 1
else:
idx = 0
chosen = rem.pop(idx)
if chosen == m: count_m -= 1
That avoids searching.
But we need to sort before each pop. Sorting rearranges indices, so we need to sort, then pop. That's fine.
Steps:
- temp = sorted(rem) # but we need to update rem. Actually we can do rem.sort().
- then if candidate condition, pop appropriate index.
However, after sorting, the list order is defined. But if we sort each iteration, we lose original order but that's fine because we only care about multiset.
So we can do:
for i in range(1, n-1):
rem.sort()
if rem[0] == m and count_m == 1:
chosen = rem.pop(1) # take second smallest
else:
chosen = rem.pop(0)
if chosen == m:
count_m -= 1
result[i] = chosen
But careful: If count_m > 1 and rem[0] == m, we pop index 0. That removes one m, and we decrement count_m. That's correct.
But what about the scenario where the smallest element is m but count_m > 1, we pop index 0. That's fine.
Now one more nuance: In the case where rem[0] is m and count_m == 1, we pop index 1. But what if the element at index 1 is also m? That would imply count_m > 1 because there are at least two m's at indices 0 and 1. But count_m == 1, contradiction. So it's safe.
Edge: When count_m == 0? That can't happen because we need at least one m to place at the end. But if M == m and we removed one M, count_m = n-1, which is >=1. So always at least 1.
Thus algorithm is robust.
Now we should test with some random cases to ensure lexicographically smallest.
But wait: There is also the possibility that after removing one M, the rem contains elements that are equal to m, but also elements that are equal to M (if multiple M). Since M > m, these are large. In greedy, we always pick smallest possible. That's correct.
Now we need to output the sequence as space-separated integers.
Let's test with some cases:
Case 1: n=6, a = [5,5,1,2,2,3]? Actually create scenario with duplicates of both. Let's compute manually.
Input: n=6, a = [5,5,1,2,2,3]. M=5, m=1.
Remove one 5, rem = [5,1,2,2,3]. count_m=1.
Result[0]=5.
Loop i=1..4 (since n-2=4):
i=1: rem sorted [1,2,2,3,5]. smallest=1, count_m=1 -> skip, take index1=2. chosen=2, pop(1) -> remove first 2? Actually sorted: [1,2,2,3,5], index1 is 2. pop(1) removes the element at index1 which is 2 (the first 2). rem becomes [1,2,3,5]? Wait after pop: list = [1,2,3,5]? Actually original sorted: indices:0:1,1:2,2:2,3:3,4:5. pop(1) removes the element at index1 (first 2). Resulting list: [1,2,3,5]. OK. count_m unchanged. result[1]=2.
i=2: rem sorted [1,2,3,5]. smallest=1, count_m=1 -> skip, take index1=2. pop(1) removes 2. rem becomes [1,3,5]. result[2]=2? Wait we popped 2, but there is only one 2 left? Actually original had two 2's, we removed one, now there is one 2 left? But after i=1, rem was [1,2,3,5]? Wait we need to recalc: after i=1, we had rem = [1,2,3,5] (since we popped a 2). That list has one 2. Sorting yields [1,2,3,5]. So at i=2: smallest=1, count_m=1 -> skip, take index1=2 (value 2). pop(1) removes 2. rem becomes [1,3,5]. result[2]=2.
i=3: rem sorted [1,3,5]. smallest=1, count_m=1 -> skip, take index1=3. pop(1) removes 3. rem becomes [1,5]. result[3]=3.
i=4: rem sorted [1,5]. smallest=1, count_m=1 -> skip, take index1=5. pop(1) removes 5. rem becomes [1]. result[4]=5.
Now result[5] = rem[0] = 1.
Sequence: [5,2,2,3,5,1]. Is that lexicographically smallest? Let's consider alternatives. We need first 5, last 1. The remaining numbers: [5,2,2,3,1] but must end with 1. To minimize lex order, we want x2 as small as possible. Smallest possible x2? It could be 1? But if we put 1 at position2, then we would have to keep one 1 for last? Actually there is only one 1. So if we put 1 at position2, last would not be 1. So not allowed. Next smallest is 2. So x2=2 is minimal. Then given x2=2, we want x3 minimal. After using one 2, we have remaining: [5,2,3,1] (with last must be 1). Can we set x3=1? No, because that would use the only 1. So next smallest is 2 (if available). We have another 2, so x3=2 is possible. That is minimal. After using two 2's, remaining [5,3,1]. Now x4 minimal? Could be 1? But cannot, must save 1 for last. So next smallest is 3. So x4=3. Then x5 must be 5 (since remaining [5,1] and we need last 1, so x5=5). So sequence: 5,2,2,3,5,1. That matches our greedy. Could there be a sequence like 5,2,3,2,5,1? Compare at position3: 2 vs 3, ours has 2 which is smaller. So ours is smaller. So it seems correct.
Now consider a case where there are multiple m's and some numbers equal to something else. Example: a = [10, 0,0,1,2] n=5. M=10, m=0. After remove 10, rem = [0,0,1,2]. count_m=2.
result[0]=10.
i=1: rem sorted [0,0,1,2]. smallest=0, count_m=2>1 -> pop(0) -> chosen=0, count_m=1. rem becomes [0,1,2]. result[1]=0.
i=2: rem sorted [0,1,2]. smallest=0, count_m=1 -> skip, take index1=1. pop(1) -> chosen=1, count_m unchanged. rem becomes [0,2]. result[2]=1.
i=3: rem sorted [0,2]. smallest=0, count_m=1 -> skip, take index1=2. pop(1) -> chosen=2. rem becomes [0]. result[3]=2.
result[4]=0.
Sequence: [10,0,1,2,0]. Let's check alternative: Could we have [10,0,0,1,2]? Last=2 not 0, invalid. [10,0,0,2,1] last=1 invalid. [10,0,1,0,2] last=2 invalid. So ours seems smallest: after 10, we have 0, then 1. Could we have 0,0,1,2? That would be [10,0,0,1,2] but last not 0. To have last 0, we need to save one 0. So earliest we can place a 0 is at position2; we can also place second 0 at position3 or later. But we want minimal x2=0 (good). Now x3: after using one 0, we have remaining [0,1,2]. The smallest possible x3? Could we place 0? Yes, because there is still one 0 left, and we could place it at position3, but then we need to save one 0 for last? Actually if we place the second 0 at position3, then we would have no 0 left for last, and last would be something else, invalid. So we cannot place the last 0 early. So x3 cannot be 0 because that would consume the only remaining 0. So the smallest possible x3 is 1. So our greedy picks 1, correct. So sequence [10,0,1,2,0] is smallest. Could there be [10,0,1,0,2]? Last 2 invalid. So yes.
Now test case where there are multiple M and multiple m. a = [5,5,1,1,2] n=5. M=5,m=1. After removing one 5, rem = [5,1,1,2]. count_m=2.
result[0]=5.
i=1: rem sorted [1,1,2,5]. smallest=1, count_m=2>1 -> pop(0) -> chosen=1, count_m=1. rem=[1,2,5]. result[1]=1.
i=2: rem sorted [1,2,5]. smallest=1, count_m=1 -> skip, take index1=2. pop(1)-> chosen=2, rem=[1,5]. result[2]=2.
i=3: rem sorted [1,5]. smallest=1, count_m=1 -> skip, take index1=5. pop(1)-> chosen=5, rem=[1]. result[3]=5.
result[4]=1.
Sequence: [5,1,2,5,1]. Check alternatives: Could we have [5,1,1,2,5]? last=5 not 1 invalid. [5,1,1,5,2] last=2 invalid. [5,1,2,1,5] last=5 invalid. [5,1,5,1,2] last=2 invalid. [5,2,1,1,5]? x2=2 >1 so larger. So ours seems smallest.
Now what about a scenario where the smallest element after skipping m is not unique? That's fine; we pick the smallest among those > m.
Now ensure the algorithm works for n up to 100.
Now we should also consider if there are negative numbers. The greedy only compares values, works.
Now one nuance: Lexicographically smallest sequence means we compare numbers as integers. So negative numbers are smaller than positive. That is fine.
Now let's test a case where M is negative? For example, all numbers negative. Then M is the maximum (closest to zero) and m is the minimum (most negative). For instance: a = [-5, -10, -3] -> M=-3, m=-10. After remove -3, rem = [-5, -10]. count_m=1 (since m=-10). result[0] = -3.
i=1: rem sorted [-10, -5]. smallest = -10, count_m=1 -> skip, take index1 = -5. So result[1] = -5, rem=[-10]. result[2]=-10. Sequence: [-3, -5, -10]. Let's check if any other sequence with max value? Value = -3 - (-10) = 7. Alternative: [-3, -10, -5] would have x2=-10 which is smaller? Lexicographically, we compare [-3, -5, -10] vs [-3, -10, -5]. At position2: -5 vs -10, since -5 > -10? Actually lexicographically, we compare numbers, and we want the smallest sequence. At index2, -10 is less than -5 (because -10 < -5). So [-3, -10, -5] would be lexicographically smaller? Let's examine: Sequence A: [-3, -5, -10]; Sequence B: [-3, -10, -5]. At position1 both -3. At position2: A has -5, B has -10. Since -10 < -5, B is lexicographically smaller. But is B valid? Check: x1 = -3 (M), x_n =? For B: x = [-3, -10, -5], last is -5, but m = -10, so last is not m. So B does NOT achieve maximum value because x1 - x_n = -3 - (-5) = 2, not 7. So B is not valid. So the lexicographically smallest among valid sequences is A. Our algorithm produced A.
But could there be a valid sequence with x2 = -10? That would require last = m = -10, but if we put -10 at position2, we need to keep another -10 for last? But there is only one -10. So can't. So indeed x2 cannot be -10. So -5 is the smallest possible x2. Good.
Now consider a scenario where M and m are both negative and there are duplicates of m. Example: a = [-3, -10, -10, -5]. M=-3, m=-10. After remove -3, rem = [-10, -10, -5]. count_m=2.
result[0] = -3.
i=1: sorted [-10, -10, -5]. smallest = -10, count_m=2>1 -> pop(0) -> chosen=-10, count_m=1, rem=[-10, -5]. result[1] = -10.
i=2: sorted [-10, -5]. smallest=-10, count_m=1 -> skip, take index1=-5, pop(1) -> chosen=-5, rem=[-10]. result[2] = -5.
result[3] = -10.
Sequence: [-3, -10, -5, -10]. Check alternatives: Could we have [-3, -10, -10, -5]? Last=-5 not -10 invalid. [-3, -5, -10, -10]? x2=-5 > -10? Actually -5 > -10, so lex larger. So ours is smallest.
Now what about a case where M is positive, m is negative, and there are many numbers, and the greedy picks negative numbers early if possible. That's consistent.
Now we need to confirm that the greedy algorithm indeed yields the lexicographically smallest sequence. As argued, it picks the smallest possible element at each position given the constraint of saving at least one m for the end. But is there any scenario where picking the smallest available (subject to saving one m) could lead to infeasibility later? For example, suppose after picking that element, later we might be forced to place an element that makes last not m? But we argued the only constraint is that we must have at least one m left for last. As long as we maintain that, any ordering of the other elements is feasible. So picking the smallest possible at each step while maintaining that invariant should yield a valid sequence. And because we always keep the invariant (by skipping the last m), the sequence is always feasible. So the greedy is optimal.
We can formalize: At any point, the set of remaining elements is R, with known count of m. The number of positions left to fill (including the last) is k. We need to ensure that after filling these k positions, the last is m. The necessary and sufficient condition is that count_m >= 1 (obviously) and that k >= 1 (true). However, is there any additional constraint regarding the order? No, because we can always arrange the remaining elements arbitrarily, putting m at the last. So the only condition to be able to complete after choosing an element e for current position is: after removing e, we must have count_m' >= 1 (if e != m) or if e == m then count_m' >= 0 but we need at least 1 for last? Actually if we take m and there were originally c m's, after taking one, we have c-1 m's left. We need at least 1 for last, so we require c-1 >= 1, i.e., c >= 2. So the condition for taking m is that we have at least 2 m's. For any other element, we just need that after removal, we still have at least 1 m (since other elements don't reduce m count). So the greedy rule exactly checks this: we can take the smallest element if either it's not m, or it's m and count_m >= 2. If it's m and count_m == 1, we cannot take it. So that's exactly the feasibility condition for the current choice. Therefore, picking the smallest feasible element yields lexicographically smallest sequence.
Thus algorithm is sound.
Now we need to handle output format: integers separated by spaces, with a trailing space? In sample output they have a space after last number? Actually sample output: "100 -50 0 50 -100 " shows a trailing space. But usually it's okay to print without trailing space. We'll follow typical: print with spaces, maybe join with space.
Now implement:
Steps in code:
def solve():
import sys
input = sys.stdin.readline
n = int(input().strip())
a = list(map(int, input().split()))
M = max(a)
m = min(a)
# special case? not needed.
rem = a[:]
rem.remove(M) # removes first occurrence
count_m = rem.count(m)
res = [0]*n
res[0] = M
for i in range(1, n-1):
rem.sort()
if rem[0] == m and count_m == 1:
# take second smallest
val = rem.pop(1)
else:
val = rem.pop(0)
if val == m:
count_m -= 1
res[i] = val
# after loop, rem should have 1 element
res[n-1] = rem[0]
print(' '.join(map(str, res)))
But we should consider if n=2, the loop range(1, n-1) is range(1,1) which is empty, and then we set res[1] = rem[0] which is the only element. Good.
Now test with sample: output "100 -50 0 50 -100". Our join will produce "100 -50 0 50 -100". Sample had trailing space, but not important.
Now test with all equal: a = [3,3,3], n=3.
M=3,m=3, rem after remove one 3: [3,3], count_m = 2.
res[0]=3.
Loop i=1: rem sorted [3,3]. rem[0]==3 and count_m==2, so else branch -> pop(0) -> val=3, count_m becomes 1, res[1]=3, rem becomes [3].
Then res[2]=3. Sequence [3,3,3] ok.
Now test with n=2, a = [5,1]. M=5,m=1, rem after remove 5: [1], count_m=1. Loop none, res[1]=1 => [5,1].
Now test with n=2, a = [5,5] (all equal). M=5,m=5, rem after remove 5: [5], count_m=1, res=[5,5].
Works.
Now consider case where after removing M, the rem list includes multiple M's? As argued, that doesn't affect.
Now we need to ensure that we correctly handle when there are multiple copies of M and we remove one. Using list.remove(M) will remove the first occurrence. That's fine because all M are identical.
Now what if the input has multiple numbers equal to M and also equal to m? That only when all equal.
Now, one more nuance: The greedy picks smallest feasible element each time. But is it always optimal to take the smallest feasible element at each step? Yes, due to lexicographic order.
However, we should consider if there is any scenario where picking a slightly larger element at an early position could allow a smaller element at a later position, leading to a lexicographically smaller overall sequence? Lexicographic order prioritizes earlier positions, so making an earlier position larger cannot be compensated by making a later position smaller. So if we can make the current position smaller without violating feasibility, that yields a lexicographically smaller sequence. So we must choose the smallest feasible. So greedy is optimal.
Thus implementation done.
But I want to double-check the scenario where the smallest feasible element is not unique due to duplicates, but we pick one of them. Since they are equal, it doesn't matter.
Now ensure that we correctly maintain count_m. At the start, count_m = number of m in rem. But we must consider that after we remove M, m might be equal to M? In all equal case, m==M, and after removal, count_m = rem.count(m) where m = M. That's fine.
One more edge: Suppose the original array has M and m distinct, but after removing M, the rem might contain no m? That would happen if the only occurrence of m was also the maximum? But m is min, M is max, distinct, so m != M, so m cannot be equal to M. So at least one m remains. So count_m >= 1.
Now the loop's condition: if rem[0] == m and count_m == 1: we pop index 1. But suppose the smallest element is m, count_m == 1, and rem[1] also equals m? That would imply count_m >= 2, contradiction. So fine.
Now we should also consider if there is a scenario where after removal of M, the rem has only one element, and that element is m. Then n=2 case (since n-1=1). Loop not executed. Good.
Now check n=3, rem size 2. Example: a = [5,1,2] M=5,m=1. rem = [1,2], count_m=1. Loop i=1 only (since n-1=2, range(1,2) i=1):
rem sorted [1,2]. rem[0]==1 and count_m==1 => skip, pop index1 -> val=2, count_m unchanged, res[1]=2, rem becomes [1]. Then res[2]=1. Sequence [5,2,1]. Lexicographically smallest? Could we have [5,1,2]? Last=2 not 1, invalid. So [5,2,1] is only valid? Actually could we have [5,1,2]? That gives x1-x_n=5-2=3, while max is 5-1=4, so not optimal. So only valid is with last=1. So our output is correct.
Now test n=3, a = [5,5,1] M=5,m=1. rem after removing one 5: [5,1], count_m=1. Loop i=1: rem sorted [1,5]. smallest=1, count_m=1 => skip, pop index1 => val=5, rem becomes [1]. res[1]=5, res[2]=1. Sequence [5,5,1]. Could we have [5,1,5]? Last=5 not 1, invalid. So only valid. Good.
Now test n=3, a = [5,1,1] M=5,m=1. rem after removing 5: [1,1], count_m=2. Loop i=1: rem sorted [1,1], smallest=1, count_m=2>1 => pop index0 => val=1, count_m=1, rem becomes [1]. res[1]=1, res[2]=1. Sequence [5,1,1]. Valid? Check: last=1, good. Could there be [5,1,1]? Yes. Could we have [5,1,1]? Same. So output fine.
Now test n=4, a = [5,1,2,2] M=5,m=1. rem = [1,2,2] count_m=1. Loop i=1..2:
i=1: rem sorted [1,2,2] -> skip smallest, pop index1=2, rem=[1,2], res[1]=2.
i=2: rem sorted [1,2] -> skip smallest, pop index1=2, rem=[1], res[2]=2.
res[3]=1 => [5,2,2,1]. Check alternatives: Could we have [5,2,1,2]? last=2 not 1 invalid. [5,1,2,2]? last=2 invalid. So only valid is with last 1. But could we have [5,1,2,2]? That's invalid because last is 2. So our output [5,2,2,1] is the only valid? Wait, we must have last=1. But we have numbers: 5,1,2,2. To have last=1, we must place 1 at the end. The other three positions (first three) contain 5,2,2 in some order, with first must be 5. So the middle two are 2 and 2. So the sequence must be [5,2,2,1] or [5,2,2,1] (only one order since both 2's identical). So correct.
Now test scenario where there is a number equal to m but also other numbers smaller than some? Not possible.
Now everything seems fine.
But wait: There is a subtlety: The value V = x1 - x_n. But is there any arrangement that achieves M - m but does not have x1 = M and x_n = m? Let's double-check: Suppose we have M and m distinct. To get V = M - m, we need x1 - x_n = M - m. Since x1 ≤ M and x_n ≥ m, the maximum difference is M - m, achieved only when x1 = M and x_n = m. So indeed both conditions necessary.
But is it possible that M - m is achieved with x1 = M and x_n = m but also x1 might be something else if there are multiple copies? No.
So condition stands.
Now consider case where there are multiple copies of M and m. The lexicographically smallest sequence might have x1 = M (the largest value). Since M is the largest, it might be bigger than all other numbers. Lexicographically, having a large first element might seem to make the sequence larger, but we are forced to have that because we are only considering sequences that achieve max value. Among those, we want the lexicographically smallest. Since x1 is forced to be M, we cannot reduce it. So it's fine.
Now we should also check if there is any alternative arrangement that yields same V but with different ends? Could there be a scenario where x1 - x_n = M - m but x1 is not M and x_n is not m? Suppose M=10, m=0. Could we have x1=9, x_n=-1? That gives 9 - (-1)=10 = M - m, but -1 is less than m? Actually m is the minimum of the set, which is 0. So -1 is not in the set. So not allowed. So x1 and x_n must be from the set. So they must be within the multiset. So if the set contains numbers, x1 cannot be 9 if 9 is not present, etc. So indeed, to achieve M - m, we need to pick the maximum as first and minimum as last.
One might ask: Could we have x1 = M and x_n = m but also maybe some other arrangement yields same V with x1 = something else and x_n = something else if there are other numbers that also give same difference? For instance, if there are numbers such that x1 - x_n = M - m but x1 < M and x_n < m? Actually x_n cannot be less than m because m is the minimum. So x_n ≥ m. To have x1 - x_n = M - m with x1 < M, we would need x_n < m to compensate, impossible. Similarly, x_n > m would require x1 > M, impossible. So unique.
Thus our constraints are correct.
Now the algorithm seems straightforward.
But wait: The problem statement says "output the lexicographically smallest sequence x that corresponds to an arrangement of the largest possible value." So they want the permutation itself, not just value. Our algorithm gives that.
Now verify with more random tests by brute force for small n to ensure that our greedy yields lexicographically smallest among all optimal permutations. Since n ≤ 100, brute force for n up to maybe 8 or 9 is possible to test. We can write a small script to enumerate all permutations (with duplicates handled) and find max value, then among those with max value, pick lexicographically smallest, and compare to our algorithm. But given reasoning, it should match.
I'll simulate mentally a few tricky cases.
Case: a = [3,2,1] n=3. M=3,m=1. Our algorithm: rem=[2,1], count_m=1. Loop i=1: sorted [1,2] -> skip smallest, pop index1=2 -> res[1]=2, rem=[1], res[2]=1 => [3,2,1]. Brute force: All permutations: [3,2,1] value=3-1=2; [3,1,2] value=3-2=1; [2,3,1] value=2-1=1; [2,1,3] value=2-3=-1; [1,3,2] value=1-2=-1; [1,2,3] value=1-3=-2. Max=2, only [3,2,1] achieves it? Check [3,1,2] gives 1, not max. So only one optimal. So output [3,2,1] correct.
Case: a = [4,4,1,2] n=4. M=4,m=1. Our algorithm: rem=[4,1,2], count_m=1. i=1: sorted [1,2,4] -> skip, pop index1=2 -> res[1]=2, rem=[1,4]. i=2: sorted [1,4] -> skip, pop index1=4 -> res[2]=4, rem=[1]. res[3]=1 => [4,2,4,1]. Brute force: All permutations with max value? Value max = 4-1=3. Need first=4, last=1. Available numbers: two 4s, one 2, one 1. But we need to use exactly these numbers. So sequences of form [4, ?, ?, 1] with the other three numbers being {4,2,1}? Actually we must use all numbers. So we have one 4 at first, and one 1 at last. The remaining two positions: we have one 4 and one 2. So possible orders: [4,4,2,1] and [4,2,4,1]. Lexicographically compare: [4,2,4,1] vs [4,4,2,1]: at position2: 2 < 4, so [4,2,4,1] is smaller. So our output matches.
Case: a = [5,0,0,0] n=4. M=5,m=0. rem=[0,0,0], count_m=3. i=1: sorted [0,0,0], smallest=0, count_m=3>1 -> pop index0, val=0, count_m=2, rem=[0,0]. i=2: sorted [0,0], smallest=0, count_m=2>1 -> pop index0, val=0, count_m=1, rem=[0]. res[1]=0, res[2]=0, res[3]=0 => [5,0,0,0]. Alternative? Must have last=0, first=5. The remaining three zeros can be placed in any order, all zeros. So all sequences are [5,0,0,0] essentially identical. Good.
Case: a = [5,4,3,2,1] n=5. M=5,m=1. rem=[4,3,2,1], count_m=1. i=1: sorted [1,2,3,4] -> skip, pop index1=2 -> res[1]=2? Wait sorted: [1,2,3,4]; pop index1 = 2; rem becomes [1,3,4]? Actually after pop, list becomes [1,3,4]. i=2: sorted [1,3,4] -> skip, pop index1=3; rem becomes [1,4]; i=3: sorted [1,4] -> skip, pop index1=4; rem becomes [1]; res[4]=1. So sequence: [5,2,3,4,1]. But is this lexicographically smallest? Let's enumerate possibilities: need first=5, last=1. Remaining numbers: 4,3,2. The three positions 2,3,4 can be any permutation of {4,3,2}. Lexicographically smallest arrangement of these three numbers in positions 2-4 is to have the smallest possible at position2: the smallest among {2,3,4} is 2. Then at position3, given we used 2, the smallest remaining is 3, then 4. So [5,2,3,4,1] is indeed the lexicographically smallest. Good.
Now test with negative numbers and positive: a = [-1, -2, 3, 4] n=4. M=4,m=-2. rem=[-1,-2,3] count_m=1 (since m=-2). i=1: sorted [-2,-1,3] -> skip smallest (-2) because count_m=1, pop index1=-1 -> res[1] = -1, rem=[-2,3]. i=2: sorted [-2,3] -> skip -2, pop index1=3 -> res[2]=3, rem=[-2]; res[3]=-2. Sequence: [4,-1,3,-2]. Check alternatives: Must have first=4, last=-2. Remaining numbers: -1,3,-2. But we need last -2, so the other two positions: positions 2 and 3 can be -1 and 3. Lexicographically, we want smallest possible at position2. The options: place -1 or 3. -1 is smaller than 3, so position2 should be -1. Then position3 is 3. So [4,-1,3,-2] is correct. Good.
Now consider scenario with many numbers, and the smallest available after skipping m might be the same as m but with count_m >1, we can take m. That yields a smaller x2 than if we had to skip. So that's good.
Now, one more nuance: Lexicographically smallest sequence means we compare integers, but note that the sequence may contain negative numbers. Our algorithm handles that.
Now check if there is any scenario where our greedy might incorrectly take an element that is not the smallest feasible because of future constraints beyond just preserving at least one m? Could there be a constraint about the first element being M? We already fixed that. Could there be a constraint about the last being m? We already handle. Are there any other constraints? The value V = x1 - x_n is independent of middle. So no.
Thus the problem is solved.
However, I recall a similar problem from Codeforces (maybe "Arrangement" or "Maximum Sum of Differences"?). The solution indeed reduces to x1 = max, xn = min, and then sort the rest in ascending order but with the twist that the last must be min, so you take ascending order but ensure that if the smallest element is the only min, you skip it and place it at the end. That's essentially our greedy.
One could also think: Sort the array ascending. Then take the largest as first. Then take all elements except the smallest in ascending order, but if the smallest appears only once, we skip it and place it at the end; if it appears multiple times, we can take all but one of the smallest in the middle in ascending order, and the last smallest at the end. But careful: If we sort ascending, the array sorted ascending: [m, ... , M]. But we need first = M (largest) and last = m (smallest). So the naive would be: take M, then all other elements in ascending order except that we need m at the end, so we take ascending order of the other elements but we might have to adjust if the smallest among remaining is m. So basically: after removing one M and one m, sort the remaining. Then the sequence would be: M, then sorted remaining, then m. But is that lexicographically smallest? Let's test with sample: remaining after removing M=100 and m=-100: [50,0,-50]. Sorted remaining: [-50,0,50]. Then sequence: 100, -50, 0, 50, -100. That matches output. In the example with duplicates we tested: a = [5,1,1,2] n=4. M=5,m=1. Remove one 5 and one 1? Actually if we remove one M and one m, remaining = [1,2] (since we had two 1's, remove one 1). Sorted remaining = [1,2]. Sequence: 5,1,2,1. That matches our greedy output. But is this always correct? Let's test with a = [5,5,1,2] earlier: M=5,m=1. Remove one M and one m, remaining = [5,2] (since we had two 5's, one 1). Sorted remaining = [2,5]. Sequence: 5,2,5,1. Our greedy gave [5,2,5,1]? Actually greedy gave [5,2,5,1]? Wait earlier we had [10,2,10,1] for a similar but numbers different. For [5,5,1,2], we computed: after remove one 5, rem=[5,1,2], count_m=1, greedy gave: i=1 skip 1 -> take 2, i=2 skip 1 -> take 5 -> seq [5,2,5,1]. So that matches "sorted remaining" after removing one M and one m? But we removed only M initially for greedy, not m. In the "remove both" approach, we would have removed one M and one m, remaining = [5,2], sorted = [2,5] -> sequence [5,2,5,1] indeed. So that also works. For [5,1,1,2], remove one M and one m (one 1), remaining = [1,2], sorted = [1,2] -> sequence [5,1,2,1] matches. For [5,0,0,0], remove one M and one m? M=5,m=0, remove one 5 and one 0, remaining = [0,0] sorted = [0,0] -> sequence [5,0,0,0] matches. For [5,4,3,2,1], remove one M and one m: remaining = [4,3,2] sorted = [2,3,4] -> sequence [5,2,3,4,1] matches greedy. For [-3,-5,-10]? Actually we had [-3,-5,-10]: M=-3,m=-10. Remove M and m: remaining = [-5] sorted = [-5] -> sequence [-3,-5,-10] matches.
It seems that the simpler approach might be: Sort the array ascending. Then take the largest element (last of sorted) as first. Then take all elements except the largest and the smallest, sorted ascending, and then the smallest as last. However, if there are multiple copies of largest or smallest, we only remove one of each. That is, result = [max] + sorted(multiset without one max and one min) + [min]. This yields the sequence we got in all tests.
Is this always lexicographically smallest? Let's think. We need to minimize x2 first. After x1 = max, we want the smallest possible x2. The smallest element in the multiset overall is min. But we cannot use min if it's the only min, because we need it at the end. If there are multiple mins, we can use one min at x2. So the smallest possible x2 is either min (if count(min) >= 2) or the next smallest element (if count(min)==1). This is exactly the smallest element in the multiset after removing one max and one min (the min we reserve for the end). Because if count(min) >= 2, then after removing one min for the end, there is still at least one min left, so the smallest element in the remaining multiset (after removing one max and one min) is still min. So x2 = min is allowed. If count(min) == 1, after removing that min for the end, the smallest element in the remaining multiset (which does not include that min) is the next smallest. So x2 is the smallest element among the rest.
Similarly, for x3, after fixing x2, we want the smallest possible from what remains (still ensuring we keep at least one min if not yet placed). But if we follow the sorted order of the multiset after removing one max and one min, we are essentially taking the elements in increasing order. This seems to match the greedy we described, because the greedy also picks the smallest feasible at each step, which ends up being the sorted order of the multiset after removing one max and one min. But we need to confirm that the greedy, which operates by always taking the smallest available while keeping at least one m, will produce exactly the sorted order of the multiset after removing one max and one min. Let's reason.
We start with multiset S (original). We remove one max to fix as first. Then we have multiset T = S \ {one max}. We need to arrange T into sequence of length n-1 with last = m. Our greedy algorithm chooses at each step the smallest element in T, unless that element is the unique m, in which case it chooses the next smallest. After we choose an element, we remove it. This process, when applied to T, will produce a sequence that is exactly the sorted order of T, but with the unique m moved to the end if it is unique. More precisely, if T contains k copies of m. If k >= 2, then the smallest element is m, and we can take m repeatedly until only one m remains, then we will skip that last m and take other elements. This results in a sequence where all but one m appear in the front in sorted order, then the other elements in sorted order, and finally the last m. But is that the same as sorting T and then moving the last occurrence of m to the end? Let's see: Suppose T sorted ascending: [m, m, ..., m (k times), a1, a2, ...]. If we take the greedy approach, we will take m as long as count_m > 1. That means we take the first k-1 m's from the sorted list. Then when count_m becomes 1, we skip the last m, and start taking the next smallest elements (a1, a2, ...). At the end, we place the last m. So the final sequence (excluding the initial max) is: (k-1 copies of m) + (sorted list of non-m elements) + (one m). This is exactly the sorted list of T, but with the last m moved to the end. However, if we simply take sorted(T) and then move the last element (which is m if m is the smallest? Actually in sorted(T), the smallest elements are m's at the beginning. If we take sorted(T) as the middle sequence and then put m at the end, that would be: sorted(T) = [m, m, ..., m, a1, a2, ...], and then we also put m at the end? That would duplicate the last m? No, we need to use exactly the elements of T. So if we take sorted(T) as the middle and then put an extra m at the end, we would have an extra m. So that's wrong.
But consider the approach: Take max, then take sorted list of all elements except one max and one min, then take min. That list is: [max] + sorted(S \ {one max, one min}) + [min]. This is different from the greedy output? Let's compare with greedy output for cases where there are multiple mins. In case [5,1,1,2], S = [5,1,1,2], max=5, min=1, S \ {one max, one min} = [1,2] sorted = [1,2], sequence = [5,1,2,1]. Greedy gave [5,1,2,1]. That matches. In case [5,0,0,0], S \ {5,0} = [0,0] sorted = [0,0], sequence = [5,0,0,0]. Greedy gave same. In case [5,5,1,2], S \ {5,1} = [5,2] sorted = [2,5], sequence = [5,2,5,1]. Greedy gave same. In case [5,4,3,2,1], S \ {5,1} = [4,3,2] sorted = [2,3,4], sequence = [5,2,3,4,1]. Greedy gave same. In case sample, S \ {100, -100} = [50,0,-50] sorted = [-50,0,50], sequence = [100,-50,0,50,-100] matches. So it appears that the simple method works.
But does it always produce the same as greedy? Let's prove.
We have original multiset S. Let count_M = number of times max appears, count_m = number of times min appears.
We need to output sequence: x1 = M, x_n = m, and the middle n-2 elements are the multiset R = S \ {one M, one m} arranged in some order. We want the lexicographically smallest sequence. Since x1 is fixed, we need to minimize the sequence of the middle and the last, but the last is forced to m, so we need to minimize the middle part (positions 2..n-1) lexicographically. The middle part is a permutation of R. So we need the lexicographically smallest permutation of R as a sequence of length n-2. However, is there any additional constraint linking the middle and the last? The last is already m, separate from R. So we just need the lexicographically smallest permutation of R. That is simply the sorted ascending order of R (since lexicographic order of the whole sequence from position 2 onward is determined by the order of R; the last is fixed m, but position 2 is first element of R, etc.). To minimize the sequence (x2, x3, ..., x_{n-1}, x_n), we want x2 as small as possible, then x3 as small as possible, etc. Since x_n is fixed to m, we only need to minimize the prefix of the middle. This is achieved by sorting R in ascending order. Because if we have any permutation of R, the lexicographic order of (R_sequence, m) is determined by R_sequence; m is constant at the end. So we need the smallest R_sequence in lexicographic order, which is the sorted ascending order of R.
But wait, is there any scenario where using a different order could make the overall sequence lexicographically smaller even though the middle part is not sorted ascending? For example, suppose R = [a, b] with a < b. Sorted ascending gives [a, b]. Then the full tail is (a, b, m). If we instead use [b, a], the tail is (b, a, m). Compare: at position2, a vs b, a is smaller, so sorted ascending is lexicographically smaller. So yes, sorted ascending is optimal.
Thus the optimal arrangement is simply: x1 = max, then the remaining numbers except one min sorted in ascending order, then x_n = min. But careful: R = S \ {one M, one m}. But is it always correct to remove exactly one M and one m, regardless of counts? If count_M > 1, we still remove one M for first, and R will contain the other M's. That's fine. If count_m > 1, we remove one m for last, and R contains the other m's. Sorting R ascending will place those extra m's at the beginning of the middle (since they are smallest). That matches the greedy approach: we can place some m's early because we have extra copies. So yes.
Thus the solution reduces to:
Find max element M and min element m.
Remove one occurrence of M and one occurrence of m from the multiset.
Sort the remaining elements in non-decreasing order.
Output: M, then the sorted list, then m.
But we need to be careful: In the case where M == m (all equal), then removing one M and one m leaves n-2 elements (all equal). Sorted order is same. Then output: M, then (n-2) copies of M, then m (=M). That's fine. That sequence is lexicographically smallest? Since all numbers equal, any order gives same, so it's fine.
Now check if any nuance: For n=2, after removing one M and one m, the remaining list is empty. So output: M, then (empty), then m => [M, m]. That's correct.
Thus the problem has a very simple solution.
But wait, is it always valid to remove one M and one m? Yes, because we need to place one M at front and one m at end. The other elements are the rest. And the middle order can be arbitrary, and lexicographically smallest is sorted ascending.
But is there any scenario where the lexicographically smallest sequence among those with max value is not simply sorted ascending of the rest? Could there be a situation where we might want to place an element that is not the smallest at position 2 because putting the smallest at position 2 might force the last element to be something other than m? But we already reserved one m for the end. The rest R does not include that reserved m. So we are free to arrange R arbitrarily. There is no further constraint linking R to the last element because we already set aside one m. So any permutation of R is feasible. Therefore, to minimize lexicographically, we sort R ascending.
But is there any scenario where the set R includes m (because we had multiple m's) and we might want to not place an m at position 2 even though it is available, because placing it earlier might affect something else? No, because the last is already a different m (we reserved one). So placing an m early is fine. And since m is the smallest, it gives a smaller x2, which is beneficial. So we definitely want to place any extra m's as early as possible.
Thus the simple approach is correct and easier.
But we need to verify with a case where there are multiple max and min and maybe other numbers. The simple approach yields the same as greedy.
Let's test with a more complex case: a = [10,10,1,1,2,3]. n=6, M=10,m=1. Remove one 10 and one 1, remaining = [10,1,2,3] (since we had two 10s and two 1s). Sorted remaining = [1,2,3,10]. Output: [10,1,2,3,10,1]. Greedy would: start with rem after removing one 10: [10,1,1,2,3]. count_m=2. i=1: smallest 1, count_m=2>1 -> pop 1 -> res[1]=1, count_m=1, rem=[10,1,2,3]. i=2: sorted [1,2,3,10]; smallest 1 but count_m=1 -> skip, pop index1=2 -> res[2]=2, rem=[10,1,3]. i=3: sorted [1,3,10]; smallest 1 count_m=1 -> skip, pop index1=3 -> res[3]=3, rem=[10,1]. i=4: sorted [1,10]; smallest 1 count_m=1 -> skip, pop index1=10 -> res[4]=10, rem=[1]; res[5]=1. Sequence: [10,1,2,3,10,1] matches.
Now what if we had a case where there is only one m but many M, and many numbers in between. Simple: remove one M and one m, sort remaining. That yields x2 as the smallest among remaining (which is the second smallest overall, since smallest is m removed). That's exactly what greedy does (skip m, take next smallest). So it matches.
Thus the simplified solution is correct.
But wait, does this always produce lexicographically smallest? Consider the full sequence: x1 = M, x2..x_{n-1} = sorted(R), x_n = m. Compare with any other valid sequence: Any valid sequence must have x1=M, x_n=m. The middle part is some permutation of R. Since sorted ascending is the lexicographically smallest permutation of R (as a list), and the last element is the same m, the overall sequence (M, perm(R), m) will be lexicographically smaller if perm(R) is lexicographically smaller. So yes.
Thus we can implement simply.
One nuance: When M == m, R = S minus two copies? Actually if all equal, then removing one M and one m leaves n-2 copies. Sorting them yields ascending (all same). Output: M, then n-2 copies of M, then m (which is M). So sequence is all M's. That's fine.
But what about the case where n=1? Not allowed (n>=2).
Now we need to ensure that we remove exactly one occurrence of M and one occurrence of m from the list. Since list may have duplicates, we need to do that correctly. In Python, we can use list.remove(M) to remove one occurrence, and then list.remove(m) to remove one occurrence. However, careful: If M == m, then after first removal, the list still contains m (since all are m). Then we call remove(m) again, which will remove another occurrence. That's correct. So we can do:
temp = a[:]
temp.remove(M)
temp.remove(m)
But if M != m, and there is only one m, after removing M, we have m present, so remove(m) works. If there is only one M and M != m, removing M works, then remove(m) works.
Potential issue: If M == m and n=2, then after removing one M, temp has size 1 (the other M). Then we call temp.remove(m) (m equals M). This will remove the last element, leaving empty list. That's fine.
Thus code can be:
def solve():
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
M = max(a)
m = min(a)
# create a copy
rem = a[:]
rem.remove(M)
rem.remove(m)
rem.sort()
res = [M] + rem + [m]
print(' '.join(map(str, res)))
But wait: In the case where M == m, we are removing two copies, but what if n=2 and M == m? Then rem becomes empty, sorted empty, res = [M] + [] + [m] = [M, m] but since M==m, it's [value, value]. That's correct. For n=2 and M != m, after removal, rem empty, res = [M, m] correct.
Now check for n=3 with distinct: a = [5,1,2]. M=5, m=1. rem after removal: [2]. sorted = [2], res = [5,2,1]. That's correct. Our earlier greedy gave [5,2,1] as well. Good.
Now check for n=3 with duplicates: a = [5,5,1]. M=5,m=1. rem after removal: remove one 5 -> list becomes [5,1]; then remove one 1 -> list becomes [5]. sorted = [5], res = [5,5,1]. Good.
Now test for n=3 with a = [5,1,1]. M=5,m=1. remove one 5 -> [1,1]; remove one 1 -> [1]; sorted = [1]; res = [5,1,1]. Good.
Now test for n=4 with a = [5,5,1,1]. M=5,m=1. remove one 5 -> [5,1,1]; remove one 1 -> [5,1]; sorted = [1,5]? Actually after removal: first remove M: list becomes [5,1,1] (since we had two 5's, remove one). Then remove m: remove one 1 -> list becomes [5,1] (since there are two 1's initially). So rem = [5,1]. sort -> [1,5]. res = [5,1,5,1]. That's lexicographically smallest? Let's see alternatives: Must have first=5, last=1. Remaining numbers: 5,1. So middle two are 5 and 1. Lexicographically, we want x2 as small as possible: 1 is smaller than 5, so sequence [5,1,5,1] is smaller than [5,5,1,1]. So correct.
Now consider a = [5,2,2,1] we did earlier: remove M=5,m=1 -> rem = [2,2] sorted = [2,2], res = [5,2,2,1] correct.
Now consider a = [5,0,0,0]: remove 5, then remove one 0 -> rem = [0,0] sorted = [0,0], res = [5,0,0,0] correct.
Now consider a with negative: a = [-1,-2,3,4] -> M=4,m=-2. remove 4 -> [-1,-2,3]; remove -2 -> [-1,3]; sorted = [-1,3]? Actually sort -> [-1,3]. res = [4,-1,3,-2]. That's the same as greedy output. Good.
Now we must confirm that this simple method is always valid even when the smallest element appears only once. In that case, we remove that one m for the last, and the remaining R does not contain any m. So sorted R will start with the second smallest element. That's exactly what we need to minimize x2. Good.
Now think about lexicographic order: Is it possible that there is a sequence with same prefix as ours but with a different arrangement of R that yields a smaller sequence due to the last element being different? But last element is fixed to m, so no.
Thus the solution is trivial: output max, then sorted remaining after removing one max and one min, then min.
But wait: Is there any scenario where the sorted order of R is not the lexicographically smallest permutation of R? Typically, the lexicographically smallest permutation of a multiset is the sorted ascending order. Yes.
Thus we can implement.
But hold on: The problem statement asks for "lexicographically smallest sequence x". That means we compare the entire sequence x1..xn. Since x1 is fixed to M, and xn to m, the only freedom is in the middle. So sorted ascending middle is indeed smallest.
Now, is there any tricky case where we could achieve the same maximum value with a different choice of ends? Could we possibly have x1 not equal to max but still achieve M - m? As argued, no. So the ends are forced.
Thus the solution is simple.
But before finalizing, let's double-check the telescoping sum: V = (x1 - x2) + (x2 - x3) + ... + (x_{n-1} - x_n) = x1 - x_n. That's clear.
Thus problem is solved.
Now we must output the sequence. Implementation note: Use list.remove() which removes first occurrence. Since we only care about values, it's fine.
But caution: In Python, if the list does not contain the element, remove raises ValueError. But we know M and m are present. However, if M == m and there is only one element? n>=2, so there are at least two elements. If M == m, then the list has at least two copies of that value, so removing two is fine. But if n=2 and M==m, then a = [x, x]. After removing first x, the list has one x. Removing second x works. So fine.
Now, one more nuance: The sorted order of R: In Python, sort() sorts in ascending order. That's what we want.
Now, test with n=100, values within range. This should be fast.
Thus final answer: read n, read list, compute max and min, remove one each, sort remainder, output max, sorted remainder, min.
Now also note: The problem statement might have ambiguous requirement about trailing spaces, but it's okay.
Thus final solution is very short.
But is there any scenario where this simple approach fails because the sequence we output might not be a permutation of original? Let's verify: We used original list, removed one max and one min, then we output max, then the sorted remaining, then min. The multiset of output is exactly {max} ∪ (remaining) ∪ {min} = original set. So it's a permutation.
Now confirm for edge case where max and min are the same, and we remove two copies, then output max, sorted remaining (which are the rest), and min. That's correct.
Thus we can produce final answer.
Now before finalizing, let's reflect: Did we miss any potential case where there might be multiple maximum value arrangements with same x1 - x_n but not necessarily with x1 = max and x_n = min? For instance, if the set has multiple values, could we have x1 = some value a, x_n = b such that a - b = M - m but a < M and b > m? That would require a - b = M - m, but since a ≤ M and b ≥ m, the only way is a = M and b = m. Because suppose a = M - d, b = m + e, with d,e ≥ 0. Then a - b = (M - d) - (m + e) = (M - m) - (d + e). To equal M - m, we need d + e = 0 => d=0, e=0. So indeed unique.
Thus no other.
Now we can confidently answer.
But wait, I recall a problem from Codeforces: "Maximum sum of differences" or "Arrangement" might have additional twist? Let's re-read the problem statement: "You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers. More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The value of such an arrangement is (x1 - x2) + (x2 - x3) + ... + (xn - 1 - xn). Find the largest possible value of an arrangement. Then, output the lexicographically smallest sequence x that corresponds to an arrangement of the largest possible value."
Yes, exactly.
Thus our solution is correct.
Now we should produce final answer.
But I think there might be a subtlety: The lexicographically smallest sequence is defined for sequences of numbers. Sorting the middle ascending yields the smallest sequence. However, what about the possibility that there is an alternative arrangement that also yields the same max value but with a different first element? No, as argued.
Thus final answer.
We will implement solve() as described.
Now consider time complexity: O(n log n) due to sorting. n ≤ 100, trivial.
Now we can write final solution.
But before writing final, let's test with some random cases using brute force in mind to be absolutely sure. Let's enumerate all permutations for n=5 with some multiset and check.
Case: a = [3,3,2,2,1] (M=3,m=1). Our algorithm: remove one 3 and one 1 -> remaining = [3,2,2] sorted = [2,2,3]; output = [3,2,2,3,1]. Let's list all optimal arrangements (first=3, last=1) and compare lexicographically.
All permutations of remaining {3,2,2} for positions 2,3,4. The possibilities (since two 2's are identical, only distinct orders are based on where the 3 goes): sequences:
A: [3,2,2,3,1]
B: [3,2,3,2,1]
C: [3,3,2,2,1]
Now lexicographically compare:
Compare A and B: x1=3 equal, x2=2 equal, x3: A has 2, B has 3 -> since 2 < 3, A is smaller.
Compare A and C: x2: A has 2, C has 3 -> 2 < 3, so A smaller.
Thus A is smallest. So our output A is correct.
Case: a = [4,3,2,1] M=4,m=1. Our algorithm: remove 4 and 1 -> remaining = [3,2] sorted = [2,3]; output = [4,2,3,1]. Alternative optimal sequences: must have first=4, last=1, middle [3,2] in any order: [4,3,2,1] and [4,2,3,1]. Lexicographically: compare at x2: 2 vs 3, 2 is smaller, so [4,2,3,1] is smaller. Correct.
Case: a = [5,4,3,2] M=5,m=2. Remove 5 and 2 -> remaining [4,3] sorted = [3,4] -> output [5,3,4,2]. Alternative: [5,4,3,2] value=5-2=3; compare: [5,3,4,2] vs [5,4,3,2]: x2: 3 < 4, so ours is smaller. Correct.
Case with multiple mins: a = [5,1,1,2,3] M=5,m=1. Remove 5 and one 1 -> remaining = [1,2,3] (since two 1's, remove one, left one 1). Sorted = [1,2,3]; output = [5,1,2,3,1]. Alternatives: Must have first=5, last=1. The remaining multiset is {1,2,3}. We need to arrange positions 2-4 as a permutation of these three. Lexicographically smallest sequence of these three (as a permutation) is [1,2,3] (since 1 is smallest possible at position2, then with remaining {2,3}, smallest is 2, etc.) So output is indeed smallest.
Case with multiple max: a = [5,5,1,2,3] M=5,m=1. Remove one 5 and one 1 -> remaining = [5,2,3] sorted = [2,3,5]; output = [5,2,3,5,1]. Alternatives: first=5, last=1, remaining {5,2,3}. Permutations: sorted ascending is [2,3,5] gives sequence [5,2,3,5,1]. Compare with [5,3,2,5,1] -> x2 2 < 3 so ours smaller; with [5,2,5,3,1] -> at x3: ours 3 vs 5, 3<5, so ours smaller; with [5,5,2,3,1] -> x2: 2 vs 5, ours smaller; with [5,5,3,2,1] -> x2:2<5; with [5,3,5,2,1] -> x2:2<3. So ours is smallest.
Thus all good.
Now we should also consider case where the max and min are the same, but there are other numbers? That's impossible because if max = min then all numbers are equal. So that's covered.
Now consider n=2 with distinct: [5,1] -> output [5,1] correct.
Now consider n=2 with equal: [5,5] -> output [5,5] correct.
Thus solution is final.
Now we can produce final answer with code.
But wait: There might be a catch: The definition of "lexicographically smallest" might treat negative numbers differently? No, integers are compared as usual.
Now implement.
One more check: The sample output has a trailing space. Usually judges ignore trailing spaces. So we can just join.
Thus final code.
Now provide explanation in final answer.
We'll write:
The value simplifies to x1 - x_n.
Maximum possible is max(a) - min(a), achieved only when x1 = max, x_n = min.
Then among such arrangements, to minimize lexicographically, we fix x1 = max, x_n = min, and arrange the rest in non-decreasing order (since that yields smallest possible x2, x3, ...).
Implementation: remove one occurrence of max and one of min from the list, sort the rest, output max, sorted rest, min.
Edge case when all equal works.
Now we can finalize.
But I just thought: What about the scenario where after removing max and min, the remaining list is empty (n=2). Then output just max and min. That's fine.
Thus final answer.
Now produce final output. ```python
import sys
def solve() -> None:
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
mx = max(a)
mn = min(a)
code
# remove one occurrence of mx and one of mn
rem = a[:]
rem.remove(mx)
rem.remove(mn)
rem.sort()
result = [mx] + rem + [mn]
print(' '.join(map(str, result)))